Python字符串作为子进程的文件参数

Python字符串作为子进程的文件参数,python,string,file,subprocess,Python,String,File,Subprocess,我试图将一个文件传递给一个程序(MolPro),该程序是用Python作为子进程启动的 它通常以文件作为参数,在控制台中如下所示: path/molpro filename.ext 其中filename.ex包含要执行的代码。另一种选择是bash脚本(我正在尝试使用Python执行此操作): 所以我很确定输入看起来不像是一个文件,但即使是查看我也找不到我做错了什么 我不想: 将字符串写入实际文件 将shell设置为True (我无法更改MolPro代码) 非常感谢你的帮助 更新:如果有人尝

我试图将一个文件传递给一个程序(MolPro),该程序是用Python作为子进程启动的

它通常以文件作为参数,在控制台中如下所示:

path/molpro filename.ext
其中filename.ex包含要执行的代码。另一种选择是bash脚本(我正在尝试使用Python执行此操作):

所以我很确定输入看起来不像是一个文件,但即使是查看我也找不到我做错了什么

我不想:

  • 将字符串写入实际文件
  • 将shell设置为True
  • (我无法更改MolPro代码)
非常感谢你的帮助


更新:如果有人尝试做同样的事情,如果您不想等待作业完成(因为它不会返回任何结果),请使用
p.stdin.write(StdinCommand)

如果从
Popen()
参数中删除
StdinCommand
,则第二种方法应该可以工作:

p = Popen(['/vol/thchem/x86_64-linux/bin/molpro'], shell = False, stdout = None, stderr = STDOUT, stdin = PIPE)
p.communicate(input = StdinCommand)

为什么要在实际的命令行上提供大量的文本块,
StdinCommand
?方法2提供了stdin上的文本。你为什么在命令行上重复它?因为一个错误,我已经忽略了一个小时左右…:-)
from subprocess import Popen, STDOUT, PIPE
DEVNULL = open('/dev/null', 'w')  # I'm using Python 2 so I can't use subprocess.DEVNULL
StdinCommand = '''
    MolPro code
'''

# Method 1 (stdout will be a file)
Popen(['path/molpro', StdinCommand], shell = False, stdout = None, stderr = STDOUT, stdin = DEVNULL)
# ERROR: more than 1 input file not allowed

# Method 2
p = Popen(['path/molpro', StdinCommand], shell = False, stdout = None, stderr = STDOUT, stdin = PIPE)
p.communicate(input = StdinCommand)
# ERROR: more than 1 input file not allowed
p = Popen(['/vol/thchem/x86_64-linux/bin/molpro'], shell = False, stdout = None, stderr = STDOUT, stdin = PIPE)
p.communicate(input = StdinCommand)