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

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

本文介绍了Python字符串作为子流程的文件参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文件传递给我作为Python子进程启动的程序(MolPro).

I am trying to pass a file to a program (MolPro) that I start as subprocess with Python.

最常见的是将文件作为参数,例如在控制台中:

It most commonly takes a file as argument, like this in console:

path/molpro filename.ext

其中filename.ex包含要执行的代码.另一种bash脚本(我正在尝试使用Python进行此操作):

Where filename.ex contains the code to execute. Alternatively a bash script (what I'm trying to do but in Python):

#!/usr/bin/env bash
path/molpro << EOF
    # MolPro code
EOF

我正在尝试在Python中完成上述操作.我已经尝试过了:

I'm trying to do the above in Python. I have tried this:

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

因此,我很确定输入看起来不像文件一样,甚至可以查看我找不到我在做什么错误的.

So I am pretty sure the input doesn't look enough like a file, but even looking at Python - How do I pass a string into subprocess.Popen (using the stdin argument)? I can't find what Im doing wrong.

我不愿意:

非常感谢您的帮助!

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

推荐答案

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

It seems like your second method should work if you remove StdinCommand from the Popen() arguments:

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

这篇关于Python字符串作为子流程的文件参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!