【问题标题】:Python command interpreterPython 命令解释器
【发布时间】:2015-02-12 18:51:56
【问题描述】:

我有一个 python 脚本,我想以这种方式从 bash 脚本运行:

#!/bin/bash
python -c "$(< input_file)" &> output_file

在 python 脚本中我有一些不同的方法,所以输入文件包含如下内容:

from script import *; method_1(); method_2();

问题是,在这两种方法中,它们都有一个需要用户输入的input() 方法(无法更改)。

那么我如何在input_file(某种换行参数)中传递一个参数,以便将它传递给method_1()method_2() 中的input() 方法?

【问题讨论】:

  • -c 参数后面的 python 命令行上的任何参数都被解释为传递给 python 代码的参数(即 input_file 中的任何代码)。因此,您可以让input_file 中的代码从命令行读取参数,然后在&amp;&gt; output_file 部分之前发送您喜欢的任何内容。

标签: python linux bash command-line interpreter


【解决方案1】:

一个方便的方法是使用“here document”:

$ cat myscript
#!/bin/bash
python -c "$(< input_file)" &> output_file << END
3
4
END

这是一个独立的测试用例:

$ cat input_file
height = input("Height:\n")
width = input("Width:\n")
print "Area: ", height*width

$ bash myscript
(no output)

$ cat output_file 
Height:
Width:
Area:  12

【讨论】:

    【解决方案2】:

    我相信input 函数只是从标准输入中读取。

    因此,您应该能够将数据通过管道(或重定向)到该 python 调用,以便 input 接收我想。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-30
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 2010-10-06
      • 2015-04-04
      • 2011-10-27
      相关资源
      最近更新 更多