Foros del Web » Programando para Internet » Python »

Seguro que es algo muy facil pero.....

Estas en el tema de Seguro que es algo muy facil pero..... en el foro de Python en Foros del Web. Hola: Este es mi primer post en este foro. No soy programador ni nada similar y he entrado en este foro para una consulta que ...
  #1 (permalink)  
Antiguo 03/11/2010, 17:02
 
Fecha de Ingreso: noviembre-2010
Mensajes: 6
Antigüedad: 13 años, 5 meses
Puntos: 0
Seguro que es algo muy facil pero.....

Hola: Este es mi primer post en este foro.

No soy programador ni nada similar y he entrado en este foro para una consulta que a lo mejor les puede paracer tonta.

Me han pasado un script hecho con pyton y no se ejecutarlo correctamente.

En concreto no se la sintaxis que hay que poner para que el script se ejecute. Uso windows XP y desde la pantalla de Dos ejecuto el scritp

C:\Python27>python kiwi.py
usage: kiwi [-v|-x] [-o outputdir] -d <dvd directory>
-v list modules contained in the LOADING.KWI FILE
-x extract modules from the LOADING.KWI file
-d directory where the DVD is mounted
-o target dir to extract modules into

Y el resultado es

C:\Python27>python kiwi.py [-v|-x] [-o C:\KWI\] -d <g:\>
La sintaxis del comando no es correcta.

Me pueden decir que he de poner siendo:

C:\KWI : la ruta donde quiero que se extraiga el archivo
G:\ la ruta donde esta puesto el DVD.

Saludos
  #2 (permalink)  
Antiguo 03/11/2010, 17:36
 
Fecha de Ingreso: julio-2010
Mensajes: 46
Antigüedad: 13 años, 8 meses
Puntos: 0
Respuesta: Seguro que es algo muy facil pero.....

Por lo que veo ya tienes el interprete de Python instalado.

Lo único que tienes que hacer es dirigirte a donde tienes el script (.py) y poner:
python nombre_script.py

Saludos
  #3 (permalink)  
Antiguo 03/11/2010, 18:19
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años
Puntos: 1360
Respuesta: Seguro que es algo muy facil pero.....

Los corchetes significa que es opcional. Los pipes | o tuberias significa que tienes varias opciones. los <> significa que es necesario.

En este caso:
python kiwi.py -vx -o C:\KWI\ -d g:\
  #4 (permalink)  
Antiguo 04/11/2010, 02:59
 
Fecha de Ingreso: noviembre-2010
Mensajes: 6
Antigüedad: 13 años, 5 meses
Puntos: 0
Respuesta: Seguro que es algo muy facil pero.....

Cita:
Iniciado por razpeitia Ver Mensaje
Los corchetes significa que es opcional. Los pipes | o tuberias significa que tienes varias opciones. los <> significa que es necesario.

En este caso:
python kiwi.py -vx -o C:\KWI\ -d g:\
Gracias, ya he avanzado un paso.

Si lo uso tal cual lo pones me lleva al principio del script

C:\Python27>python kiwi.py -vx -o C:\Python27\kwi\ -d g:\
usage: kiwi [-v|-x] [-o outputdir] -d <dvd directory>
-v list modules contained in the LOADING.KWI FILE
-x extract modules from the LOADING.KWI file
-d directory where the DVD is mounted
-o target dir to extract modules intos

Si le quito la varible X entonces si opera y al menos lista lo modulos que hay en el archivo Loading.

C:\Python27>python kiwi.py -v -o C:\Python27\kwi\ -d g:\
number of systems found: 1
System 1
Manufacturer ID: 0f 56 a3 00 3c 3c 8a 00 07 00 01 66
Number of modules in this system: 7
Module 1:
Name: V206
Version: 101A
Category: Program
Valid from: 2010-06-21
Address: 0x1000
Size: 15.2 MB

ETC....

Pero si lo dejo con la variable -x para que haga la extracion de los modulos pasa esto:

C:\Python27>python kiwi.py -x -o C:\Python27\kwi\ -d g:\
Error: global name 'kiwi' is not defined

Y esta es la operacion mas importante ya que lo que tengo que modificar son los archivos .bin que lleva ese archivo loading.kwi
  #5 (permalink)  
Antiguo 04/11/2010, 10:02
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años
Puntos: 1360
Respuesta: Seguro que es algo muy facil pero.....

Acabo de buscar el script y me encontre con esto me puse a leerlo un poco y vi donde tenia el error te dejo el modificado. Si falla algo vuelve a postear
Código:
#!/usr/bin/env python
#
#       kiwi
#
#       Copyright 2009 Bert Vermeulen <[email protected]>
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import os
import sys
from getopt import getopt
import string
from datetime import datetime
import struct

EXTRACT_BUFSIZE = 1024 * 1024


def usage():
	print """usage: kiwi [-v|-x] [-o outputdir] -d <dvd directory>
  -v	list modules contained in the LOADING.KWI FILE
  -x	extract modules from the LOADING.KWI file
  -d	directory where the DVD is mounted
  -o	target dir to extract modules into"""
	sys.exit(1)


def is_printable(text):
	for i in text:
		if i not in string.printable + '\x00':
			return False

	return True


def show_date(stamp):
	date = datetime.fromtimestamp(stamp)
	datestr = "%d-%.2d-%.2d" % (date.year, date.month, date.day)

	return datestr


def maybe_dump(text):
	if is_printable(text):
		return text
	else:
		hex = ''
		for i in text:
			hex += "%.2x " % int(ord(i))
		return hex


def show_kwi_info(lo):
	print "number of systems found:", lo['num_systems']
	syscnt = 1
	for s in lo['systems']:
		print "System %s\n    Manufacturer ID: %s" % (syscnt, maybe_dump(s['mid']))
		print "    Number of modules in this system:", len(s['modules'])
		modcnt = 1
		for modname, modversion, category, startdate, enddate, title, info, address, size in s['modules']:
			print "    Module %d:" % modcnt
			print "\tName:", modname
			print "\tVersion:", modversion
			print "\tCategory:", category
			if startdate:
				print "\tValid from:", show_date(startdate)
			if enddate:
				print "\tValid until:", show_date(enddate)
			print "\tAddress: 0x%X" % address
			size += 0.0
			if size > 1024 * 1024:
				size /= 1024 * 1024
				unit = "MB"
			elif size > 1024:
				size /= 1024
				unit = "KB"
			else:
				unit = "bytes"
			print "\tSize: %.1f %s" % (size, unit)

			print
			modcnt += 1

		syscnt += 1


def extract_modules(path, targetdir, system=1):
	try:
		#lo = kiwi.parse_loading(path) #kiwi no defined
                lo = parse_loading(path)
		if lo['num_systems'] < system:
			raise Exception, "only %s systems found" % lo['num_systems']

		if not os.path.exists(targetdir):
			os.mkdir(targetdir)

		s = lo['systems'][system-1]
		print "extracting modules into %s..." % targetdir
		fp = open(path)
		for modname, modversion, category, startdate, enddate, title, info, address, size in s['modules']:
			print "  ", modname
			fp.seek(address)
			cnt = 0
			outfile = open(targetdir + '/' + modname, 'w')
			while True:
				if cnt + EXTRACT_BUFSIZE > size:
					chunksize = size - cnt
				else:
					chunksize = EXTRACT_BUFSIZE
				buf = fp.read(chunksize)
				outfile.write(buf)
				cnt += chunksize
				if len(buf) < EXTRACT_BUFSIZE:
					break
			outfile.close()
		fp.close()
	except Exception, msg:
		print "Error:", str(msg)


module_categories = [
	'Initial program',
	'Program',
	'Library',
	'Data'
]

def parse_loading(path):
	lostruct = {}
	fp = open(path)
	data = fp.read(4)
	num_systems, dummy = struct.unpack_from(">HH", data)
	lostruct['num_systems'] = num_systems
	offset = 4
	lostruct['systems'] = []
	for s in range(num_systems):
		system = {}
		fp.seek(offset)
		data = fp.read(16)
		mid, num_modules, dummy = struct.unpack_from(">12sHH", data)
		offset += 16
		system['mid'] = mid
		system['modules'] = []
		# get Module Identification Information blocks
		for m in range(num_modules):
			fp.seek(offset)
			data = fp.read(64)
			cat, modname, modversion = struct.unpack_from(">cxxx52s4s", data)
			offset += 64
			cat = ord(cat)
			category = module_categories[cat & 3]
			if cat & 64:
				category += " (Test module)"
			if cat & 128:
				category += " (Diagnostic service module)"
			modname = modname.rstrip('\x00')
			system['modules'].append([modname, modversion, category])
		# get Module Management Information blocks
		address_multiplier = 0
		for m in range(num_modules):
			fp.seek(offset)
			data = fp.read(256)
			startdate, enddate, title, info, address, size = struct.unpack_from(">HH64s182sIH", data)
			offset += 256
			# dates are in number of days since 1997-01-01 00:00:00. that's
			# 852073200 seconds since the unix epoch, convert to that
			# if it's 0 no date is set, so preserve that
			if startdate:
				startdate += 852073200 + (startdate * 86400)
			if enddate:
				enddate += 852073200 + (enddate * 86400)
			# address is either in 2048-byte sized blocks, or some odd 3-byte
			# block size. try to grok this by the first one we
			# see, which will be right past this this Loading Module Management
			# block we're parsing now
			if m == 0:
				if address < 0x100:
					# too small to be an absolute address
					address_multiplier = 2048
				elif (address >> 8) < 0x100:
					address_multiplier = 8
				else:
					address_multiplier = 1
			address *= address_multiplier
			# size is in 2048-byte sized blocks
			size *= 2048
			system['modules'][m] += [startdate, enddate, title, info, address, size]
		lostruct['systems'].append(system)

	return lostruct




#
# main
#

opts, args = getopt(sys.argv[1:], "vxd:o:")

mode = dvddir = targetdir = None
for opt, arg in opts:
	if opt == '-v':
		if mode:
			usage()
		else:
			mode = 'view'
	elif opt == '-x':
		if mode:
			usage()
		else:
			mode = 'extract'
	elif opt == '-d':
		dvddir = arg
	elif opt == '-o':
		targetdir = arg

if not mode or not dvddir:
	usage()

try:
	path = dvddir + '/LOADING.KWI'
	if not os.path.exists(path):
		print "no LOADING.KWI found in %s" % dvddir
		sys.exit(1)
except Exception, msg:
	print "failed to open %s: %s" % (path, str(msg))
	sys.exit(1)
else:
	if mode == 'view':
		kwi_info = parse_loading(path)
		show_kwi_info(kwi_info)
	elif mode == 'extract':
		if not targetdir:
			print "please set a target directory to extract into."
			usage()
		else:
			extract_modules(path, targetdir)
Edito: Guarda este codigo como kiwi2.py y solo haz un python kiwi2.py -x -o C:\Python27\kwi\ -d g:\

Última edición por razpeitia; 04/11/2010 a las 14:02
  #6 (permalink)  
Antiguo 05/11/2010, 03:17
 
Fecha de Ingreso: noviembre-2010
Mensajes: 6
Antigüedad: 13 años, 5 meses
Puntos: 0
Respuesta: Seguro que es algo muy facil pero.....

Cita:
Iniciado por razpeitia Ver Mensaje
Acabo de buscar el script y me encontre con esto me puse a leerlo un poco y vi donde tenia el error te dejo el modificado. Si falla algo vuelve a postear

Edito: Guarda este codigo como kiwi2.py y solo haz un python kiwi2.py -x -o C:\Python27\kwi\ -d g:\
Muchas gracias, ahora funciona la extraccion pero con problema. Extrae varios archivos de solo 1k que al abrirlos en wordpad o ultraedit solo llevan el nombre del archivo y poco mas.

Dentro del a7 rchivo LOADING hay varios archivos binarios (modulos). Este script es para listar y extraer esos archivos. Al usar el script para listar esos archivos figuran 7 archivos o modulos y se puede ver el tamaño de cada uno:

Number of modules in this system: 7
Module 1:
Name: V206
Version: 101A
Category: Program
Valid from: 2010-06-21
Address: 0x1000
Size: 15.2 MB

Module 2:
Name: V214
Version: 101A
Category: Program
Valid from: 2010-06-21
Address: 0xF3F800
Size: 15.7 MB

Module 3:
Name: V308
Version: 101A
Category: Program
Valid from: 2010-06-22
Address: 0x1EE9800
Size: 20.6 MB

Module 4:
Name: V309
Version: 101A
Category: Program
Valid from: 2010-06-22
Address: 0x337B800
Size: 20.5 MB

Module 5:
Name: V312
Version: 101A
Category: Program
Valid from: 2010-06-22
Address: 0x47F9000
Size: 18.9 MB

Module 6:
Name: V443
Version: 101A
Category: Program
Valid from: 2010-06-22
Address: 0x5AE6000
Size: 19.0 MB

Module 7:
Name: V453
Version: 101A
Category: Program
Valid from: 2010-06-22
Address: 0x6DE0800
Size: 19.6 MB

Pero al extraerlos solo sale un archivo de 1KB con el nombre del modulo.

Mas tarde voy a subir a rapidshare el archivo LOADING por si por favor le puedes hechar un vistazo y puedes llegar a extraer esos archivos.

Gracias, gracias, gracias
  #7 (permalink)  
Antiguo 06/11/2010, 08:52
 
Fecha de Ingreso: noviembre-2010
Mensajes: 6
Antigüedad: 13 años, 5 meses
Puntos: 0
Respuesta: Seguro que es algo muy facil pero.....

Ya he subido el archivo LOADING.KWI del que quiero extraer los modulos o archivos binarios que van dentro. Si algun alma caritativa piuede mirar el script para que los pueda extraer de forma adecuada le estare muy agradecido yo y cientos de personas que al igual que yo estan en lo mismo.

El enlace es este: http://rapidshare.com/files/428226679/LOADING_2011.KWI

Última edición por NotasNotas; 06/11/2010 a las 08:53 Razón: Me falto poner el enlace
  #8 (permalink)  
Antiguo 06/11/2010, 19:26
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años
Puntos: 1360
Respuesta: Seguro que es algo muy facil pero.....

Código:
#!/usr/bin/env python
#
#       kiwi
#
#       Copyright 2009 Bert Vermeulen <[email protected]>
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import os
import sys
from getopt import getopt
import string
from datetime import datetime
import struct

EXTRACT_BUFSIZE = 1024 * 1024


def usage():
	print """usage: kiwi [-v|-x] [-o outputdir] -d <dvd directory>
  -v	list modules contained in the LOADING.KWI FILE
  -x	extract modules from the LOADING.KWI file
  -d	directory where the DVD is mounted
  -o	target dir to extract modules into"""
	sys.exit(1)


def is_printable(text):
	for i in text:
		if i not in string.printable + '\x00':
			return False

	return True


def show_date(stamp):
	date = datetime.fromtimestamp(stamp)
	datestr = "%d-%.2d-%.2d" % (date.year, date.month, date.day)

	return datestr


def maybe_dump(text):
	if is_printable(text):
		return text
	else:
		hex = ''
		for i in text:
			hex += "%.2x " % int(ord(i))
		return hex


def show_kwi_info(lo):
	print "number of systems found:", lo['num_systems']
	syscnt = 1
	for s in lo['systems']:
		print "System %s\n    Manufacturer ID: %s" % (syscnt, maybe_dump(s['mid']))
		print "    Number of modules in this system:", len(s['modules'])
		modcnt = 1
		for modname, modversion, category, startdate, enddate, title, info, address, size in s['modules']:
			print "    Module %d:" % modcnt
			print "\tName:", modname
			print "\tVersion:", modversion
			print "\tCategory:", category
			if startdate:
				print "\tValid from:", show_date(startdate)
			if enddate:
				print "\tValid until:", show_date(enddate)
			print "\tAddress: 0x%X" % address
			size += 0.0
			if size > 1024 * 1024:
				size /= 1024 * 1024
				unit = "MB"
			elif size > 1024:
				size /= 1024
				unit = "KB"
			else:
				unit = "bytes"
			print "\tSize: %.1f %s" % (size, unit)

			print
			modcnt += 1

		syscnt += 1


def extract_modules(path, targetdir, system=1):
	try:
		#lo = kiwi.parse_loading(path) #kiwi no defined
		lo = parse_loading(path)
		if lo['num_systems'] < system:
			raise Exception, "only %s systems found" % lo['num_systems']

		if not os.path.exists(targetdir):
			os.mkdir(targetdir)

		s = lo['systems'][system-1]
		print "extracting modules into %s..." % targetdir
		#fp = open(path) #This doesn't open the file in binary mode
		fp = open(path, "rb")
		for modname, modversion, category, startdate, enddate, title, info, address, size in s['modules']:
			print "  ", modname
			fp.seek(address)
			cnt = 0
			#outfile = open(targetdir + '/' + modname, 'w') ##This doesn't open the file in binary mode
			outfile = open(targetdir + '/' + modname, 'wb')
			while True:
				if cnt + EXTRACT_BUFSIZE > size:
					chunksize = size - cnt
				else:
					chunksize = EXTRACT_BUFSIZE
				buf = fp.read(chunksize)
				outfile.write(buf)
				cnt += chunksize
				if len(buf) < EXTRACT_BUFSIZE:
					break
			outfile.close()
		fp.close()
	except Exception, msg:
		print "Error:", str(msg)


module_categories = [
	'Initial program',
	'Program',
	'Library',
	'Data'
]

def parse_loading(path):
	lostruct = {}
	fp = open(path)
	data = fp.read(4)
	num_systems, dummy = struct.unpack_from(">HH", data)
	lostruct['num_systems'] = num_systems
	offset = 4
	lostruct['systems'] = []
	for s in range(num_systems):
		system = {}
		fp.seek(offset)
		data = fp.read(16)
		mid, num_modules, dummy = struct.unpack_from(">12sHH", data)
		offset += 16
		system['mid'] = mid
		system['modules'] = []
		# get Module Identification Information blocks
		for m in range(num_modules):
			fp.seek(offset)
			data = fp.read(64)
			cat, modname, modversion = struct.unpack_from(">cxxx52s4s", data)
			offset += 64
			cat = ord(cat)
			category = module_categories[cat & 3]
			if cat & 64:
				category += " (Test module)"
			if cat & 128:
				category += " (Diagnostic service module)"
			modname = modname.rstrip('\x00')
			system['modules'].append([modname, modversion, category])
		# get Module Management Information blocks
		address_multiplier = 0
		for m in range(num_modules):
			fp.seek(offset)
			data = fp.read(256)
			startdate, enddate, title, info, address, size = struct.unpack_from(">HH64s182sIH", data)
			offset += 256
			# dates are in number of days since 1997-01-01 00:00:00. that's
			# 852073200 seconds since the unix epoch, convert to that
			# if it's 0 no date is set, so preserve that
			if startdate:
				startdate += 852073200 + (startdate * 86400)
			if enddate:
				enddate += 852073200 + (enddate * 86400)
			# address is either in 2048-byte sized blocks, or some odd 3-byte
			# block size. try to grok this by the first one we
			# see, which will be right past this this Loading Module Management
			# block we're parsing now
			if m == 0:
				if address < 0x100:
					# too small to be an absolute address
					address_multiplier = 2048
				elif (address >> 8) < 0x100:
					address_multiplier = 8
				else:
					address_multiplier = 1
			address *= address_multiplier
			# size is in 2048-byte sized blocks
			size *= 2048
			system['modules'][m] += [startdate, enddate, title, info, address, size]
		lostruct['systems'].append(system)

	return lostruct




#
# main
#

opts, args = getopt(sys.argv[1:], "vxd:o:")

mode = dvddir = targetdir = None
for opt, arg in opts:
	if opt == '-v':
		if mode:
			usage()
		else:
			mode = 'view'
	elif opt == '-x':
		if mode:
			usage()
		else:
			mode = 'extract'
	elif opt == '-d':
		dvddir = arg
	elif opt == '-o':
		targetdir = arg

if not mode or not dvddir:
	usage()

try:
	path = dvddir + '/LOADING.KWI'
	if not os.path.exists(path):
		print "no LOADING.KWI found in %s" % dvddir
		sys.exit(1)
except Exception, msg:
	print "failed to open %s: %s" % (path, str(msg))
	sys.exit(1)
else:
	if mode == 'view':
		kwi_info = parse_loading(path)
		show_kwi_info(kwi_info)
	elif mode == 'extract':
		if not targetdir:
			print "please set a target directory to extract into."
			usage()
		else:
			extract_modules(path, targetdir)
A mi me funciono muy bien, solo tuve que cambiar la manera en que abría los archivos. Dime si te funciona.
  #9 (permalink)  
Antiguo 07/11/2010, 15:07
 
Fecha de Ingreso: noviembre-2010
Mensajes: 6
Antigüedad: 13 años, 5 meses
Puntos: 0
Respuesta: Seguro que es algo muy facil pero.....

Cita:
Iniciado por razpeitia Ver Mensaje
A mi me funciono muy bien, solo tuve que cambiar la manera en que abría los archivos. Dime si te funciona.
EUREKA

EUREKA

Extracion correcta.

No sabes cuanto te lo agradezco. También a quien hizo el script original pero se ve que con errores, que tu haz corregido perfectamente y que ya le he enviado al creador original, aunque no se si recibe mis correos por que nunca me ha contestado.

No se de donde eres pero si alguna vez pasas por España, concretamente por Murcia no dejes de enviarme un mensaje, la invitacion a comer es mia.

Poca gente dedica su tiempo a ayudar a otros como tu lo has hecho.

Gracias y saludos.
  #10 (permalink)  
Antiguo 07/11/2010, 15:52
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años
Puntos: 1360
Respuesta: Seguro que es algo muy facil pero.....

Muchas gracias por la invitación.

En mi Ubicación dice Monterrey, México. Ahora ya sabes de donde soy :P
  #11 (permalink)  
Antiguo 07/11/2010, 16:12
 
Fecha de Ingreso: noviembre-2010
Mensajes: 6
Antigüedad: 13 años, 5 meses
Puntos: 0
Respuesta: Seguro que es algo muy facil pero.....

Cita:
Iniciado por razpeitia Ver Mensaje
Muchas gracias por la invitación.

En mi Ubicación dice Monterrey, México. Ahora ya sabes de donde soy :P
Pues no me habia fijado.

Por aqui no hay muchos mejicanos, pero tengo muy buenas impresiones de algunos mejicanos que conocí en estados unidos el año pasado, gente muy agradable y siempre dispuesta a ayudar.

Saludos

Etiquetas: facil, seguro
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 09:39.