¡Esta es una revisión vieja del documento!
Utilización del lenguaje para un propósito concreto.
execfile(script_path)
path = r'c:\bsplayer' # ruta del ejecutable import os print os.execv((path), []) # lanza un ejecutable del sistema, el segundo parámetro son los argumentos para este. def start (program, *args): return os.spawnv(os.P_NOWAIT, program, (program,) + args) start(path) # lanza un ejecutable del sistema, en Windows funciona mejor que execcv. os.system(path) # lanza un comando mostrando por pantalla la salida de este import subprocess subprocess.Popen([path,'']) # una tercera forma
import os path = os.getcwd() # ruta del script name = sys.argv[0] # nombre del script exec = path + os.sep + name # ruta completa del script
import subprocess s1 = subprocess.check_output('ls') s2 = subprocess.check_output(['ls', '-la']) subprocess.getstatusoutput('ls /bin/ls') # (0, '/bin/ls') subprocess.getoutput(cmd)
import urllib data = urllib.urlopen(url).read()
import urllib url = 'http://xxxxxxxxxxxxx' params = urllib.urlencode({ 'appid': appid, 'context': context, 'query': query }) data = urllib.urlopen(url, params).read()
import urllib2 delicious_user = 'Your del.icio.us username' delicious_pass = 'Your del.icio.us password' password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() password_manager.add_password( None, 'https://api.del.icio.us/', delicious_user, delicious_pass ) auth_handler = urllib2.HTTPBasicAuthHandler(password_manager) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) xml = urllib2.urlopen('https://api.del.icio.us/v1/posts/recent').read()
atexit permite indicar una función que se llamará al finalizar la ejecución:
import atexit def all_done(): print 'all_done()' print 'Registering' atexit.register(all_done) print 'Registered'
Este código dará como resultado:
Registering Registered all_done()
Podemos pasar parámetros:
import atexit def my_cleanup(name): print 'my_cleanup(%s)' % name atexit.register(my_cleanup, 'first') atexit.register(my_cleanup, 'second') atexit.register(my_cleanup, 'third')
Se ha de detectar la KeyboardInterrup:
try: start_thread() except (KeyboardInterrupt, SystemExit): cleanup_stop_thread(); sys.exit()
Para UNIX existe el paquete netifaces:
from netifaces import interfaces, ifaddresses, AF_INET for ifaceName in interfaces(): addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )] print '%s: %s' % (ifaceName, ', '.join(addresses))
Derivado de este código cómo conseguir una ip pública:
from netifaces import interfaces, ifaddresses, AF_INET for ifaceName in interfaces(): for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'127.'}] ): if not i['addr'].startswith("127."): return i['addr']
python -m modulo. Por ejemplo, si quisiesemos abrir un servidor web en el directorio actual:$ python -m SimpleHTTPServer $ python -m SimpleHTTPServer 8080 $ python -m http.server
print map(int, "10 20 30".split()) # [10, 20, 30]
d = [1, 3, 5] d[-1] # 5
winners = set('''washington adams jefferson jefferson madison madison monroe monroe adams jackson jackson vanburen harrison polk taylor pierce buchanan'''.split())
def __init__(self, email, content, created=None): self.email = email self.content = content self.created = created or datetime.datetime.now() # if created has value self.created will take it, if not self.created will be datetime.now()
>>> a = ['a', 'b', 'c']
>>> c = [10, 33, 44]
>>> zip(a, c)
[('a', 10), ('b', 33), ('c', 44)]
>>> dict(zip(a, c))
{'a': 10, 'c': 44, 'b': 33}