亲爱的堆栈溢出用户,
我正在寻找一个可能很容易解决的问题的解决方案。我想自动化一些量子化学计算,遇到了一个小问题。
通常,您使用远程服务器上的输入文件(*.inp)作为后台进程启动您的量子化学程序(在我的例子中称为orca),并通过
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
发布于 2018-08-30 11:52:10
为什么不简单地:
subprocess.Popen(f'orca {input_file} >& {output_file}',
shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
更多信息:运行过程,不要等待
发布于 2018-08-30 13:52:15
对于我(WindowsPython2.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
作为参数列表。
发布于 2018-08-30 11:33:39
不久前我也遇到了同样的问题。这是我的解决方案:
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异常非常重要,因为您现在从未知道操作系统可能会做什么错误。
要了解更多有关真正启动进程的communicate()命令,请阅读:https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate
https://stackoverflow.com/questions/52095801
复制相似问题