【发布时间】:2015-10-02 07:47:33
【问题描述】:
我已升级到 Python 3.4.2 和 argparse(来自 optparse),但似乎都无法识别命令行选项。作为一个简单的测试,我运行它;
#test_argparse.py
def main():
import argparse
parser = argparse.ArgumentParser(description='Execute database query.')
parser.add_argument("-q", "--query", dest="query",
help="Name of the query file to be run")
args = parser.parse_args()
print(args)
if __name__ == '__main__':
main()
从命令行,当我运行时
test_argparse.py -q get_msre_for_book
我明白了:
Namespace(query=None)
但是当我从 IDE 中运行时:
*** Python 3.4.2rc1 (v3.4.2rc1:8711a0951384, Sep 21 2014, 21:16:45) [MSC v.1600 32 bit (Intel)] on win32. ***
Command Line : -q get_msre_for_book
Namespace(query='get_msre_for_book')
我正在尝试通过
启动脚本os.system('python.exe', '<path to script>test_argparse.py -q get_msre_for_book')
但这失败了,因为没有查询如上所示。我已经通过使用来解决这个问题
subprocess.call
但我宁愿不必这样做。再次感谢任何建议或想法。
【问题讨论】:
-
听起来像是 Windows 命令行问题。我会导入
sys,并打印sys.argv以检查解析器必须使用的命令行字符串。 -
好的,当我运行
test_argparse.py -q get_msre_for_book时添加了print(sys.argv),我现在得到Namespace(query=None)和['Y:\\Python\\test_argparse.py']所以它确实似乎是命令行有问题。 -
并在 ide 中
Command Line : -q get_msre_for_trader_book2Namespace(query='get_msre_for_trader_book2')['Y:\\Python\\test_argparse.py', '-q', 'get_msre_for_trader_book2'] -
但是在另一个 Windows 7 机器上,运行 optparse 和 Python 2.6.6 它可以按预期工作
(<Values at 0x20c81e8: {'query': 'test'}>, []) ['N:\\Python\\test_optparse.py', '-q', 'test'] -
早期有关于在 Windows 7 中传递命令行参数的 SO 问题。解决方案涉及正确获取注册表链接。 stackoverflow.com/questions/2640971,stackoverflow.com/questions/9880540。例如,
"C:\Python\Python33\python.exe" "%1" %*.
标签: python-3.x command-line-arguments argparse