【问题标题】:Can I access sys.argv in python in interactive mode?我可以在 python 中以交互模式访问 sys.argv 吗?
【发布时间】:2014-02-26 20:28:02
【问题描述】:

我想做这样的事情:

% python foo bar
import sys
sys.argv

得到:

%  ['foo', 'bar']

但是当你输入一个不是脚本的参数或者进入非交互模式时,python当然会死掉。

我可以这样做吗?

【问题讨论】:

    标签: python read-eval-print-loop argv


    【解决方案1】:

    使用- 作为脚本名称:

    python - foo bar
    

    测试:

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

    【讨论】:

      【解决方案2】:
      $ 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 早在 20 多岁时...!
      【解决方案3】:

      这样运行python:

      python - foo bar
      

      然后

      import sys
      sys.argv
      

      会工作:)

      【讨论】:

        【解决方案4】:

        您可以手动设置它以在 IDLE 中进行测试:

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

        【讨论】:

        • 我想过这一点,但我真的是一个偶尔的 python 程序员,我想验证我是否正确使用了数组。我通常只是编写打印语句并运行脚本,但在命令行上执行此操作会很好......
        • 但运行 python foo bar 不会运行 python
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-21
        • 1970-01-01
        • 2016-03-25
        • 1970-01-01
        • 1970-01-01
        • 2012-06-23
        • 1970-01-01
        相关资源
        最近更新 更多