在Python中调用shell命令,你可以使用`os`模块或`subprocess`模块。以下是使用这些模块调用shell命令的几种方法:
使用`os`模块
1. `os.system(cmd)`
2. `os.popen(cmd)`
执行shell命令,返回命令的输出结果。
3. `os.popen(cmd).read()`
读取命令的输出结果。
使用`subprocess`模块
1. `subprocess.run(cmd, shell=True)`
执行shell命令,并等待其完成。
2. `subprocess.check_output(cmd, shell=True)`
执行shell命令,并返回命令的输出结果。
3. `subprocess.run(cmd, capture_output=True, text=True)`
执行shell命令,并捕获命令的输出结果。
注意事项
当使用`shell=True`时,命令会在shell中执行,这可能会增加安全风险,特别是当命令包含用户输入时。
当命令包含空格或特殊字符时,建议使用`shell=True`。
使用`subprocess`模块时,建议使用`capture_output=True`和`text=True`来捕获命令的输出。
示例代码
import subprocess
使用subprocess.run执行shell命令并捕获输出
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
使用subprocess.check_output执行shell命令并获取输出
output = subprocess.check_output('ls -l', shell=True)
print(output.decode('utf-8'))
请根据你的需求选择合适的方法来调用shell命令