我正在尝试将文件传递给我作为 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
所以我很确定输入看起来不够像文件,但即使查看 Python - 如何将字符串传递给 subprocess.Popen(使用 stdin 参数)? 我找不到我在做什么错了.
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字符串作为子进程的文件参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!