【问题标题】:using input from file in subprocess.call doesnt work while os.system does在 os.system 使用 subprocess.call 中的文件输入时不起作用
【发布时间】:2020-04-18 05:23:34
【问题描述】:

我正在尝试为一个非常古老的 FORTRAN 程序创建一个 python3 包装器。本质上,我需要运行程序并将文件中的输入直接输入到这样的程序中(从命令行)。

programname < input.txt

这没有问题。当我尝试在 python os.system 中执行此操作时,但 subprocess.call 没有。当我使用 subprocess.call 时,我卡住了,程序只是坐在那里等待输入,即使它应该已经有了它。

为什么不直接使用 os.system 呢?我需要有一个执行时间限制。有时 FORTRAN 代码会在内部卡住,然后就坐在那里。如果它没有在 5 秒内完成,我需要它被杀死。据我了解,os.system 不能强制执行限制,但 subprocess.call 可以,所以这就是我所追求的。

我使用 python 程序作为 FORTRAN 程序的代理重新创建了它。这是此代码(pythonInput.py):

some_input = input("Enter some input: ") 
print(some_input)

然后用任何东西创建一个输入文件,这就是我使用的(input.txt)

RealName

从命令行可以正常工作:

python pythonInput.py < input.txt

返回:

[khoopes@computer ~]$ python pythonInput.py < input.txt
Enter some input: RealName
[khoopes@computer ~]$

但是当我制作另一个使用 python 调用另一个 python 程序的脚本时,它 subprocess.call 不起作用,这是 (pythonRunTester.py) 的代码:

import subprocess
import os
os.system('python pythonInput.py < input.txt')
subprocess.call(['python', 'pythonInput.py', '<', 'input.txt'])

返回:

[khoopes@computer ~]$ python pythonRunTester.py
Enter some input: RealName
Enter some input:

os.system 工作,但 subprocess.call 没有,它只是挂在那里等待。我试过让它像这样使用 shell=True 标志:

import subprocess
import os
os.system('python pythonInput.py < input.txt')
subprocess.call(['python', 'pythonInput.py', '<', 'input.txt'], shell=True)

返回

[khoopes@computer ~]$ python pythonRunTester.py
Enter some input: RealName
Python 3.6.8 (default, Aug  7 2019, 17:28:10)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

但这也不起作用。

有什么想法可以使用 subprocess.call 或其他方式使用 os.system 强制执行时间吗?

谢谢,

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    您需要编写不带列表的整个命令:

    subprocess.call('python pythonInput.py < input.txt', shell=True)
    

    这会起作用

    【讨论】:

      【解决方案2】:

      除了@LinPy 答案,您可以将标准输入作为参数传递给call()

      x = subprocess.call(['python', 'pythonInput.py'], stdin=open("/tmp/test.txt"))
      

      【讨论】:

        猜你喜欢
        • 2021-01-30
        • 2012-06-07
        • 1970-01-01
        • 2013-01-17
        • 1970-01-01
        • 2011-09-07
        • 2019-03-23
        • 2011-10-23
        相关资源
        最近更新 更多