python调用shell命令
在Python中调用shell命令,你可以使用subprocess模块,它提供了多种方式来执行外部命令并获取其输出。以下是使用subprocess模块调用shell命令的几种常见方法:
1. 使用subprocess.run()函数:
python<p>import subprocess<p>result = subprocess.run(['ls', '-l'], capture_output=True, text=True)<p>print(result.stdout) 输出命令结果<p>print(result.returncode) 命令退出状态码<p>
2. 使用subprocess.check_output()函数:
python<p>import subprocess<p>output = subprocess.check_output(['ls', '-l'], shell=True, text=True)<p>print(output) 输出命令结果<p>
3. 使用subprocess.call()函数:
python<p>import subprocess<p>subprocess.call(['ls', '-l'], shell=True) 执行命令,不捕获输出<p>
注意事项:
当使用shell=True时,命令字符串应该被视为一个整体,这可能会增加安全风险,特别是当命令字符串来自不可信的源时。
使用capture_output=True可以捕获命令的标准输出和标准错误。
text=True参数让输出自动解码为字符串。
请确保你了解命令可能带来的安全风险,并尽可能避免使用shell=True。