【问题标题】:Python arguments cuts at < when reading from command line从命令行读取时,Python 参数在 < 处截断
【发布时间】:2013-08-28 23:16:23
【问题描述】:

我得到了一个脚本,它应该花费一些时间来执行 python-script。为简单起见,我只在命令行中提供我想要执行的实际命令作为参数。

说我打电话:

python time.py python ratatosk.py < input.txt

python time.py 之后的所有内容都是我要执行的实际命令。

但是,当阅读sys.argv 时:

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

它只返回:

Number of arguments: 3 arguments.
Argument List: ['time.py', 'python', 'ratatosk.py']

其余的论点到哪里去了?看起来 &lt; 以某种方式将其剥离。

我在 MacBook Pro 上运行 Python Python 2.7.3(v2.7.3:70274d53c1dd,2012 年 4 月 9 日,20:52:43)。

【问题讨论】:

  • &lt; 字符在操作系统级别具有特殊含义,在将参数传递给程序之前进行解释。最好为争论选择其他东西。
  • 我建议你这样做&lt;&lt;&lt;=,只是为了逃避cmd解释器。

标签: python command-line-arguments


【解决方案1】:

您需要转义

python time.py python ratatosk.py \< input.txt

使用与

【讨论】:

    【解决方案2】:

    对于 UNIX Shell,符号“

    由于符号特殊,shell转换指定的命令,到达内核的是修改后的不包含'

    您可以通过在它之前添加 \ 来转义“

    【讨论】:

      【解决方案3】:

      你遇到的是shell redirection

      &lt; 字符对 shell 具有特殊含义。这将导致被调用的程序从后面的任何内容而不是默认的stdin(通常是键盘)读取。

      Python 只关心从stdin 读取数据,而不管它来自哪里。它不应该出现在 sys.argv 中。

      在您的示例中,input.txt 可能会替代用户将数据输入您的程序,并且您的用法是正确的。

      这是一个简短的例子:

      echo.py

      text = raw_input()
      print text
      

      input.txt

      hello from the file
      

      示例运行

      $ python echo.py 
      hello from the keyboard
      hello from the keyboard
      $ python echo.py < input.txt
      hello from the file
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-17
        • 2023-03-30
        • 1970-01-01
        • 2014-05-23
        • 2011-08-06
        相关资源
        最近更新 更多