Python function calls from the bash shell or dos prompt

From DANSE

Beyond the standard way to call python from a shell (like bash)

>$ python -c "x = [1,2];print '%s' % x"

[1, 2]

If one adds a bit of code to any existing code, some nice things happen...

#file="example.py"

def x(a,b):
'''x(a,b) --> [a,b]'''
return [a,b]

def add(a,b):
'''add(a,b) --> a+b'''
return a+b

def test():
'''test code for all modules'''
print "testing x..."
print x(1,2)
print x('a','b')
print x([1,2,3],[4,5,6])
print testing add..."
print add(1,2)
print add('a','b')
print add([1,2,3],[4,5,6])
return
if __name__=='__main__':
import sys
try:
func = sys.argv[1]
except: func = None
if func:
try:
exec 'print %s' % func
except:
print "Error: incorrect syntax '%s'" % func
exec 'print %s.__doc__' % func.split('(')[0]
else: test()

then from a shell, we can test everything:

>$ python example.py

testing x...
[1, 2]
['a','b']
[[1,2,3],[4,5,6]]
testing add...
3
ab
[1, 2, 3, 4, 5, 6]

we can call a function incorrectly, and get documentation:

>$ python example.py "x(4)"

Error: incorrect syntax 'x(4)'
x(a,b) --> [a,b]

and we can call a function correctly, and get the desired response

>$ python example.py "x(4,5)"

[4, 5]

this is really cool because if the file "example.py" lives on a remote computer, we can still call it from our local computer:

>$ ssh remote.caltech.edu 'cd ~/dev/test; python example.py "x(4,5)"'

[4, 5]

now we say if we have an implimentation of the shell commands "which" or "find" (gsl.infect does), then we can get useful information like:

LOCALLY

>$ cd ~/dev/gsl/infect; python shutils.py "which('zip')"

/usr/local/bin/zip


REMOTELY

>$ ssh remote.caltech.edu "cd ~/dev/gsl/infect; python shutils.py which\(\'zip\'\)"

/usr/bin/zip

你可能感兴趣的:(function)