在Python中调用Shell命令,推荐使用`subprocess`模块。以下是使用`subprocess`模块调用Shell命令的一些方法:
1. 使用`subprocess.run()`函数:
```python
import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout) 输出命令结果
2. 使用`subprocess.check_output()`函数:
```python
import subprocess
output = subprocess.check_output(['ls', '-l'], shell=True, text=True)
print(output) 输出命令结果
3. 使用`subprocess.call()`函数:
```python
import subprocess
subprocess.call(['ls', '-l'], shell=True) 调用命令,但不捕获输出
4. 使用`subprocess.Popen()`类:
```python
import subprocess
process = subprocess.Popen(['ls', '-l'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print(stdout.decode('utf-8')) 输出命令结果
请注意,在使用`shell=True`时要格外小心,因为它可能会导致安全漏洞,特别是当命令字符串来自不可信的源时。尽可能避免使用`shell=True`,或者在使用时对输入进行严格的验证和清理