通过子进程在python中启动后台进程并将输出写入文件

时间:2018-08-30 11:21:33

标签: python subprocess

尊敬的stackoverflow用户

我正在寻找可能很简单的问题的解决方案。我想自动化一些量子化学计算,然后遇到一个小问题。

通常,您会使用远程服务器上的输入文件(* .inp)作为后台进程来启动量子化学程序(在我的情况下称为orca),并通过以下方式将输出通过管道传递到输出文件(* .out)中

nohup orca H2.inp >& H2.out &

或类似的东西。

现在,我想使用python脚本(带有一些模板)自动写入输入文件。最后,脚本应以无需停止orca即可注销服务器的方式开始计算。我尝试过

subprocess.run(["orca", input_file], stdout=output_file)

但是到目前为止,它没有用。如何“模拟”子流程模块顶部给出的命令?

致谢

更新 我有一个名为H2.xyz的文件。该脚本按点读取并分割文件名,并创建输入文件名H2.inp,然后将输出写入文件H2.out

更新2 输入文件来自* xyz文件,通过

xyzfile = str(sys.argv[1])
input_file = xyzfile.split(".")[0] + ".inp"
output_file = xyzfile.split(".")[0] + ".out"

,并通过模板在脚本内创建。最后,我想通过以下方式运行脚本:

python3 script.py H2_0_1.xyz

4 个答案:

答案 0 :(得分:0)

不久前我遇到了同样的问题。 这是我的解决方案:

commandLineCode = "nohup orca H2.inp >& H2.out &"
try:
    proc = subprocess.Popen(commandLineCode,
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            cwd = workingDir)

except OSError:
    print("Windows Error occured")
    print(traceback.format_exc())

timeoutInSeconds = 100
try:
    outs, errs = proc.communicate(timeout = timeoutInSeconds)
except subprocess.TimeoutExpired:
    print("timeout")
    proc.kill()
    outs, errs = proc.communicate()

stdoutDecode = outs.decode("utf-8")
stderrDecode = errs.decode("utf-8")

for line in stdoutDecode.splitlines():
    # write line to outputFile
if stderrDecode:
    for line in stderrDecode.splitlines():
        # write line to error log

OSError异常非常重要,因为您现在再也不会出错了。

有关实际上启动进程的communication()命令的更多信息,请阅读: https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate

答案 1 :(得分:0)

为什么不简单:

subprocess.Popen(f'orca {input_file} >& {output_file}',
                 shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

更多信息: Run Process and Don't Wait

答案 2 :(得分:0)

子流程的使用重要吗?如果没有,您可以使用os.system

在您的情况下,Python调用会非常短

os.system("nohup orca H2.inp >& H2.out &")

应该可以解决问题。

答案 3 :(得分:0)

对于我来说(Windows,Python 2.7),方法call的工作原理如下:

with open('H2.out', 'a') as out :
    subprocess.call(['orca', infile], stdout=out,
                                      stderr=out,
                                      shell=True)   # Yes, I know. But It's Windows.

在Linux上,您可能不需要shell=True作为参数列表。