【问题标题】:can't pass arguements using argparse and python 3.4.2 on Windows 7无法在 Windows 7 上使用 argparse 和 python 3.4.2 传递争论
【发布时间】: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_book2 Namespace(query='get_msre_for_trader_book2') ['Y:\\Python\\test_argparse.py', '-q', 'get_msre_for_trader_book2']
  • 但是在另一个 Windows 7 机器上,运行 optparse 和 Python 2.6.6 它可以按预期工作(&lt;Values at 0x20c81e8: {'query': 'test'}&gt;, []) ['N:\\Python\\test_optparse.py', '-q', 'test']
  • 早期有关于在 Windows 7 中传递命令行参数的 SO 问题。解决方案涉及正确获取注册表链接。 stackoverflow.com/questions/2640971stackoverflow.com/questions/9880540。例如,"C:\Python\Python33\python.exe" "%1" %*.

标签: python-3.x command-line-arguments argparse


【解决方案1】:

为了结束这个问题,以下是解决问题的 2 个 cmets:

早先有关于在 Windows 7 中传递命令行参数的 SO 问题。解决方案涉及正确获取注册表链接。 stackoverflow.com/questions/2640971,stackoverflow.com/questions/9880540。例如,“C:\Python\Python33\python.exe”“%1”%*。

修复了它 - 非常感谢 - 但准确地说,注册表项需要是 C:\Python\Python33\python.exe" "%1" %" (添加了最后的双引号)

【讨论】:

    猜你喜欢
    • 2015-12-25
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 2016-07-16
    • 2014-12-27
    • 2020-01-09
    • 1970-01-01
    相关资源
    最近更新 更多