Skip to main content
 首页 » 编程设计

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

2025年05月04日1998°冷暖

您好,我正在尝试使用以下命令从 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 一起使用,它可以防止难以调试的意外行为,并且更便于移植。