Document Actions
Send this page to somebody Print this page
Parte 8

Ejecución de programas python

#!/usr/bin/env python
print "hello world"
$ chmod u+x hello
$ ./hello
hello world

Mas lectura

Distribución de programas python usando pypi

Pypi, (Python Package Index) es un repositorio de software para el lenguaje de programación python. Actualmente hay 4018 paquetes. Ver http://pypi.python.org/pypi?%3Aaction=browse

Bajando e instalando software con easy_install

$ sudo easy_install editra
Searching for editra
Reading http://pypi.python.org/simple/editra/
Couldn't find index page for 'editra' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
Reading http://pypi.python.org/simple/Editra/
Reading http://editra.org
Reading http://editra.org/?page=download
Best match: Editra 0.3.0
Downloading http://pypi.python.org/packages/2.4/E/Editra/Editra-0.3.0-py2.4.egg#md5=08f6e328f215f520d8d44301ab299a0d
Processing Editra-0.3.0-py2.4.egg
creating /usr/lib/python2.4/site-packages/Editra-0.3.0-py2.4.egg
Extracting Editra-0.3.0-py2.4.egg to /usr/lib/python2.4/site-packages
Adding Editra 0.3.0 to easy-install.pth file
Installing Editra script to /usr/bin
Installing Editra.pyw script to /usr/bin

Installed /usr/lib/python2.4/site-packages/Editra-0.3.0-py2.4.egg
Processing dependencies for editra
Finished processing dependencies for editra


Módulo sys


Argumentos de scripts

#!/usr/bin/env python
import sys

print "El nombre del script es ", sys.argv[0]
print "El valor de argv es ", str(sys.argv)
#!/usr/bin/env python
import sys

if len(sys.argv) > 1:
    print "hay ", len(sys.argv)-1, "argumentos:"
    for arg in sys.argv[1:]:
        print arg
else:
    print "no habia argumentos!"

Usando sys para manipular el path de búsqueda

$ dir ejemplo/
uno.py
$ cat ejemplo/uno.py
def hola():
print 'hola'
 >>> import uno
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named uno
>>> import sys
>>> sys.path
['', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/workingenv.py-0.6.5-py2.5.egg',
'/usr/lib/python2.5/site-packages/archgenxml-2.0_beta8-py2.5.egg', '/usr/lib/python25.zip', '/usr/lib/python2.5',
'/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload',
'/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric',
'/usr/lib/python2.5/site-packages/PIL', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0',
'/var/lib/python-support/python2.5/gtk-2.0', '/usr/lib/python2.5/site-packages/wx-2.6-gtk2-unicode']
>>> 'ejemplo' in sys.path
False
>>> sys.path.append('ejemplo')
>>> import uno
>>> uno.hola()
hola
>>> sys.path = []
>>> import random
Error in sys.excepthook:
Traceback (most recent call last):
File "/var/lib/python-support/python2.5/apport_python_hook.py", line 30, in apport_excepthook
import apport.report, apport.fileutils
ImportError: No module named apport.report

Original exception was:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named random

Usando sys para verificar si un módulo es builtin

import sys

def dump(module):
print module, "=>",
if module in sys.builtin_module_names:
print "<BUILTIN>"
else:
module = __import__(module)
print module.__file__
dump("os")
dump("sys")
dump("string")
dump("strop")
dump("zlib")
import sys
print sys.modules.keys()
['copy_reg', '__main__', 'site', '__builtin__', 'encodings', 'encodings.encodings', 'posixpath',
'encodings.codecs', 'os.path', '_codecs', 'stat', 'zipimport', 'warnings', 'encodings.types', 'UserDict',
'encodings.utf_8', 'sys', 'codecs', 'readline', 'types', '_types', 'signal', 'apport_python_hook', 'linecache',
'posix', 'encodings.aliases', 'exceptions', 'os']

Contando Referencias de objetos

import sys

variable = 1234

print sys.getrefcount(0)
print sys.getrefcount(variable)
print sys.getrefcount(None)

Verificando sistema operativo

>>> sys.platform
'linux2'
import sys
# emulando "import os.path"

if sys.platform == "win32":
import ntpath
pathmodule = ntpath
elif sys.platform == "mac":
import macpath
pathmodule = macpath
else:
# assume it's a posix platform
import posixpath
pathmodule = posixpath

print pathmodule

Profile

>>> def greedy():
...     for i in range(10000000):
...             a = i
>>> def lessgreedy():
...     for i in xrange(10000000):
...             a = i
>>> import profile
>>> profile.run('greedy()')
         5 function calls in 2.104 CPU seconds

   Ordered by: standard name
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.500    0.500    0.500    0.500 :0(range)
        1    0.000    0.000    0.000    0.000 :0(setprofile)
        1    1.604    1.604    2.104    2.104 <stdin>:1(greedy)
        1    0.000    0.000    2.104    2.104 <string>:1(<module>)
        1    0.000    0.000    2.104    2.104 profile:0(greedy())
        0    0.000             0.000          profile:0(profiler)

>>> profile.run('lessgreedy()')
4 function calls in 1.280 CPU seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(setprofile)
1 1.280 1.280 1.280 1.280 <stdin>:1(nongreedy)
1 0.000 0.000 1.280 1.280 <string>:1(<module>)
1 0.000 0.000 1.280 1.280 profile:0(nongreedy())
0 0.000 0.000 profile:0(profiler)
>>> def profiler(frame, event, arg):
...     print event, frame.f_code.co_name, frame.f_lineno, "->", arg
>>> sys.setprofile(profiler)
return <module> 1 -> None
>>> lessgreedy()
call decode 15 -> None
c_call decode 16 -> <built-in function utf_8_decode>
c_return decode 16 -> <built-in function utf_8_decode>
return decode 16 -> (u'lessgreedy()\n', 13)
call <module> 1 -> None
...

Maximos

>>> sys.maxint
2147483647
>>> sys.getrecursionlimit()
1000
>>> def recur():
...          recur()  
>>> recur()
                        ....
                        ....
  File "<stdin>", line 2, in recur
  File "<stdin>", line 2, in recur
RuntimeError: maximum recursion depth exceeded
>>> sys.setrecursionlimit(3)
>>> recur()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in recur
  File "<stdin>", line 2, in recur
RuntimeError: maximum recursion depth exceeded
Error in sys.excepthook:
Traceback (most recent call last):
  File "/var/lib/python-support/python2.5/apport_python_hook.py", line 41, in apport_excepthook
    pr = apport.report.Report()
  File "/var/lib/python-support/python2.5/apport/report.py", line 146, in __init__
    ProblemReport.__init__(self, type, date)
  File "/var/lib/python-support/python2.5/problem_report.py", line 28, in __init__
    if date == None:
RuntimeError: maximum recursion depth exceeded in cmp

Original exception was:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in recur
  File "<stdin>", line 2, in recur
RuntimeError: maximum recursion depth exceeded

Mas lectura


Módulo OS

>>> import os
>>> print os.__doc__
OS routines for Mac, NT, or Posix depending on what system we're on.

This exports:
- all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
- os.path is one of the modules posixpath, ntpath, or macpath
- os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'
- os.curdir is a string representing the current directory ('.' or ':')
- os.pardir is a string representing the parent directory ('..' or '::')
- os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
- os.extsep is the extension separator ('.' or '/')
- os.altsep is the alternate pathname separator (None or '/')
- os.pathsep is the component separator used in $PATH etc
- os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
- os.defpath is the default search path for executables
- os.devnull is the file path of the null device ('/dev/null', etc.)

Programs that import and use 'os' stand a better chance of being
portable between different platforms. Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).

Sistema de archivos

>>> import os
>>> import posixpath
>>> import macpath
>>> import ntpath
>>> os
<module 'os' from '/usr/lib/python2.5/os.pyc'>
>>> posixpath
<module 'posixpath' from '/usr/lib/python2.5/posixpath.pyc'>
>>> macpath
<module 'macpath' from '/usr/lib/python2.5/macpath.pyc'>
>>> ntpath
<module 'ntpath' from '/usr/lib/python2.5/ntpath.pyc'>
>>> os.path
<module 'posixpath' from '/usr/lib/python2.5/posixpath.pyc'>
>>> os.path.join('home','rover','Desktop')
'home/rover/Desktop'
>>> os.path = macpath
>>> os.path.join('home','rover','Desktop')
':home:rover:Desktop'
>>> os.path = ntpath
>>> os.path.join('home','rover','Desktop')
'home\\rover\\Desktop'

Fragmento de os.py
import sys

_names = sys.builtin_module_names

# Note: more names are added to __all__ later.
__all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
"defpath", "name", "path", "devnull"]

def _get_exports_list(module):
try:
return list(module.__all__)
except AttributeError:
return [n for n in dir(module) if n[0] != '_']

if 'posix' in _names:
name = 'posix'
linesep = '\n'
from posix import *
try:
from posix import _exit
except ImportError:
pass
import posixpath as path

import posix
__all__.extend(_get_exports_list(posix))
del posix


elif 'nt' in _names:
......
......
......
 import ntpath as path
 ......


elif 'os2' in _names:
......
......
......
import os2emxpath as path
......


elif 'mac' in _names:
......
......
......
import macpath as path
......


elif 'ce' in _names:
......
......
......
import ntpath as path
......

elif 'riscos' in _names:
......
......
......
import riscospath as path
......

else:
raise ImportError, 'no os specific module found'

sys.modules['os.path'] = path
from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
devnull)

del _names

#'

Copyright (C) 2004-2007 Menttes - All Rights Reserved