在Python中,你可以使用subprocess
模块来调用命令行命令。这个模块提供了多种函数来执行外部命令并获取其输出。以下是一些常用的方法:
subprocess.run()
执行命令并等待完成:import subprocess
command = "echo 'Hello, World!'"
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
print("Command output:", result.stdout)
print("Error output:", result.stderr)
print("Return code:", result.returncode)
subprocess.Popen()
执行命令并实时获取输出:import subprocess
command = "echo 'Hello, World!'"
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
for line in iter(process.stdout.readline, ""):
print("Command output:", line.strip())
process.stdout.close()
return_code = process.wait()
print("Return code:", return_code)
注意:在使用shell=True
时,请确保你信任要执行的命令,因为它可能会导致安全漏洞。避免在不受信任的输入上使用shell=True
。
如果你需要执行多个命令,可以将它们连接在一起,如下所示:
command = "echo 'Hello, World!' && echo 'This is another command'"
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
print("Command output:", result.stdout)
print("Error output:", result.stderr)
print("Return code:", result.returncode)