我能在Python交互模式下访问sys.argv吗?

7

我想要做一些类似以下的事情:

% python foo bar
import sys
sys.argv

获取:

%  ['foo', 'bar']

当您输入的参数不是脚本或者进入非交互模式时,Python会自动停止运行。是否有办法解决这个问题呢?
4个回答

15

使用 - 作为脚本名称:

python - foo bar

测试:

>>> import sys
>>> sys.argv
['-', 'foo', 'bar']

7
$ python - asdf asdf
Python 2.7.6 (default, Feb 15 2014, 23:06:13) 
[GCC 4.8.2 20140206 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.argv
['-', 'asdf', 'asdf']
>>> 

+1 感谢回答 - ndpu 提前 20s 进入了! - shigeta

2

以这种方式运行Python:

python - foo bar

然后
import sys
sys.argv

会起作用 :)


0

你可以在 IDLE 中手动设置来进行测试:

try:
    __file__
except:
    sys.argv = [sys.argv[0], 'foo', 'bar']

我考虑过这个问题,但我只是一个偶尔使用Python的程序员,我想验证一下我是否正确地使用了数组。通常我只是编写打印语句并运行脚本,但在命令行上执行这个操作会更好。 - shigeta
但是运行 python foo bar 不会运行 Python。 - Kissiel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接