开发者

Run Python program from shell and keep variables in scope

Python has a nice execfile function inside the interpreter where you can run a program, keep all the variables in scope, and then inspect them at your leisure. However, as far as I know you can't run execfile on a program that takes arguments from the command line; if you try to include the arguments, Python throws an IOError and complains that the file (with spaces and arguments) can't be found.

Is there a开发者_如何学JAVAny way to run a Python script that takes command line arguments, and keep all of the variables in scope after the program executes? Like an execfile that takes flags?

Thanks, Kevin


You could modify sys.argv directly. The file:

# foo.py
import sys

print sys.argv

The other file:

import sys
import shlex   # thanks Matt

old_argv = sys.argv
sys.argv = shlex.split('foo.py is a happy camper')

execfile('foo.py')

Output:

$ python foo.py is a happy camper
['foo.py', 'is', 'a', 'happy', 'camper']
$ python bar.py 
['foo.py', 'is', 'a', 'happy', 'camper']

But I must say, quoting Ignacio Vazquez-Abrams:

This sounds all sorts of messed up.

I'm assuming you have your reasons though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜