温馨提示×

python os.system命令能处理输出吗

小樊
188
2024-12-08 01:50:59
栏目: 编程语言

是的,os.system() 命令可以处理输出

例如,假设您想要运行一个名为 my_script.sh 的脚本并捕获其输出:

import os command = "my_script.sh" output = os.system(command + " > output.txt 2>&1") print("Command executed with return code:", output) 

在这个例子中,我们将脚本的输出重定向到名为 output.txt 的文件中。然后,我们可以使用 os.system() 函数的返回值来检查命令是否成功执行。

如果您想要实时查看输出,可以使用 subprocess 模块。例如:

import subprocess command = "my_script.sh" process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for line in iter(process.stdout.readline, ""): print(line.strip()) return_code = process.wait() print("Command executed with return code:", return_code) 

在这个例子中,我们使用 subprocess.Popen() 函数来运行脚本,并通过 stdoutstderr 参数捕获输出。然后,我们使用 iter() 函数和 process.stdout.readline() 方法逐行读取输出,并在控制台上打印出来。最后,我们使用 process.wait() 方法等待命令执行完成,并获取其返回值。

0