【问题标题】:How to Accept Command Line Arguments With Python Using < [duplicate]如何使用 Python 接受命令行参数 < [重复]
【发布时间】:2014-10-21 21:30:29
【问题描述】:

是否可以使用&lt; 运行python 脚本并作为参数输入文件?例如,我的脚本使用以下命令python scriptname.py input.txt 和以下代码stuffFile = open(sys.argv[1], 'r') 按预期工作。

但是,如果可能的话,我希望使用以下命令行语法:python scriptname.py &lt; input.txt。现在,运行该命令只给了我一个参数,所以我可能必须在我的脚本中调整我的代码,但不确定如何。

我有一个自动系统处理这个命令,所以它需要准确。如果使用 Python 脚本可以做到这一点,我将不胜感激!

【问题讨论】:

  • 是的,这似乎解决了这个问题。谢谢。

标签: python shell terminal


【解决方案1】:

&lt; file 由 shell 处理:文件不会作为参数传递。相反,它会成为您程序的标准输入,即sys.stdin

【讨论】:

    【解决方案2】:

    当您在 shell 中使用 https://docs.python.org/2/library/fileinput.html 它显示在这篇文章中 How do you read from stdin in Python?

    【讨论】:

      【解决方案3】:

      您可以将 sys 模块的 stdin 属性用作类似文件的对象。

      【讨论】:

        猜你喜欢
        • 2013-01-08
        • 1970-01-01
        • 1970-01-01
        • 2017-02-24
        • 1970-01-01
        • 1970-01-01
        • 2012-10-04
        • 1970-01-01
        • 2017-04-03
        相关资源
        最近更新 更多