Python string as file argument to subprocess(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
所以我很确定输入看起来不够像文件,但即使查看 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.
我不喜欢:
- 将字符串写入实际文件
- 将 shell 设置为 True
- (而且我无法更改 MolPro 代码)
非常感谢您的帮助!
更新:如果有人试图做同样的事情,如果你不想等待工作完成(因为它不会返回任何东西,无论哪种方式),使用 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字符串作为子进程的文件参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python字符串作为子进程的文件参数


- YouTube API v3 返回截断的观看记录 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01