在Python中,你可以使用os
和subprocess
模块来执行Linux指令
os.system(command)
:执行系统命令,但不返回执行结果。os.popen(command).read()
:执行系统命令并读取输出结果。subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
:使用run()
函数执行系统命令,并返回一个CompletedProcess
对象,其中包含命令的输出和错误信息。subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
:使用Popen()
函数执行系统命令,并允许你与命令的输出和错误流进行交互。
以下是一些示例:
import os import subprocess # 使用os.system执行命令 os.system("ls") # 使用os.popen执行命令并读取输出 output = os.popen("ls").read() print(output) # 使用subprocess.run执行命令并获取输出 result = subprocess.run("ls", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) print(result.stdout) # 使用subprocess.Popen执行命令并与输出流交互 process = subprocess.Popen("ls", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) output, error = process.communicate() if process.returncode != 0: print(f"Error: {error}") else: print(output)
请注意,在使用这些方法时,你需要确保你的Python脚本具有执行系统命令所需的权限。在某些情况下,你可能需要使用sudo
或以其他方式提升权限。