Python command line?
Jeff Epler
jepler at unpythonic.net
Tue Jun 4 12:20:26 EDT 2002
On Tue, Jun 04, 2002 at 10:59:18AM -0500, SA wrote:
> Hi Everyone-
>
> I would like to run python code line by line using:
>
> python -c some line of code
>
> Will this work?
Probably not. For instance,
python -c 'def f(): return 3'
python -c 'print f()'
won't do the same thing as
>>> def f(x): return 3
...
>>> print f(x)
3
You probably need to use 'eval' or 'exec':
>>> gns = {'__builtins__': __builtins__}
>>> lns = {}
>>> exec "def f(): return 3" in gns, lns
>>> exec "print f()" in gns, lns
3
>>> print lns['f']() # Or access items created in the local namespace
3
Jeff
PS you escape all sorts of quoting and length-limit problems by avoiding
the likes of os.system("python -c '%s'", cmdstr) too -- for instance,
this won't work at all on NT (since ''-quoting doesn't exist in the
shell afaik) and the cmdstr of "'; echo '0wn3d" will not do what you
want on Unix.
More information about the Python-list
mailing list