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

Python string as file argument to subprocess(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

所以我很确定输入看起来不够像文件,但即使查看 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字符串作为子进程的文件参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)