【问题标题】:Python will not read sys.argvPython 不会读取 sys.argv
【发布时间】:2011-12-19 15:06:05
【问题描述】:
    import sys

    print sys.argv[1]

你好,

这可能看起来很基本,但我无法让 Python 从命令行读取任何内容。 这就是上面的代码,我输入的是:

    myfile.py helloworld

我得到的是:

    IndexError: list index out of range

它似乎对我有用一次,但不再起作用,我尝试卸载并重新安装 Python,但它仍然不起作用。

所以我的问题是,我做错了什么吗?还是我刚刚破坏了 Python?

感谢您的帮助

使用: Windows 7的 Python 2.7.2

【问题讨论】:

  • 当你只是print sys.argv 时会发生什么?通过python.exe myfile.py helloworld调用文件时它是否有效?
  • 啊,感谢您的回复,设法让它工作。有一个非常愚蠢的错误,没有将python添加到系统变量中的Path
  • 对于那些无法在 Windows 中将参数传递给脚本而不预先调用 Python 的人(例如,python foo.py a 有效,但 foo.py a 无效)滚动跳过第一个答案。跨度>

标签: python command-line-arguments sys


【解决方案1】:

启动注册表编辑器(regedit)。将 HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command 键设置为: "C:\Python26\python26.exe" "%1" %*

本解决方案来源:http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/

【讨论】:

  • 哇,这个注册表遗漏今天让我们很伤心,我们试图平衡 Python 2.7 Anaconda 和 3.4 安装。 3.4 安装程序省略了 %* 参数,但我们需要为 HKEY_CLASSES_ROOT\Applications\pythonxx.exe\shell\open\command 键和 HKEY_CLASSES_ROOT\py_auto_file\shell\open\command 键设置它
  • 感谢您的回答
【解决方案2】:

您确定按照您认为的方式调用您的 python 脚本吗?

#!/usr/bin/python
import sys

if len(sys.argv) < 2:
    print "you did not give any arguments\n"
else:
    print sys.argv[1]

返回:

$ ./foo.py 
you did not give any arguments

$ ./foo.py hello_world
hello_world
$ 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    相关资源
    最近更新 更多