gpt4 book ai didi

python - 重定向通过python执行的shell脚本的输出

转载 作者:太空宇宙 更新时间:2023-11-04 08:18:21 25 4
gpt4 key购买 nike

您好,我正在尝试使用以下命令从 python 执行 shell 脚本。

os.system("sh myscript.sh")

在我的 shell 脚本中,我已经编写了一些 SOP,现在如何在我的 Python 中获取 SOP,以便我可以将它们记录到某个文件中?

我知道使用 subprocess.Popen 我可以做到,但出于某种原因我不能使用它。

p=subprocess.Popen(
'DMEARAntRunner \"'+mount_path+'\"',
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
while 1:
line=p.stdout.readline()[:-1]
if not line:
break
write_to_log('INFO',line)
p.communicate()

最佳答案

如果我正确理解你的问题,你想要这样的东西:

import subprocess
find_txt_command = ['find', '-maxdepth', '2', '-name', '*.txt']
with open('mylog.log', 'w') as logfile:
subprocess.call(find_txt_command, stdout=logfile, shell=False)

如果需要,您可以使用 Popen 代替 call,语法非常相似。请注意,该命令是一个列表,其中包含您要运行的进程和参数。通常,您希望将 Popen/call 与 shell=False 一起使用,它可以防止难以调试的意外行为,并且更便于移植。

关于python - 重定向通过python执行的shell脚本的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10177587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com