在Python中调用shell命令,您可以使用以下几种方法:
1. 使用`os.system`函数:
```python
import os
os.system('ls') 运行ls命令
2. 使用`os.popen`函数:
```python
import os
with os.popen('ls') as pipe:
output = pipe.read()
print(output) 输出ls命令的结果
3. 使用`subprocess`模块:
```python
import subprocess
result = subprocess.run(['ls'], capture_output=True, text=True)
print(result.stdout) 输出ls命令的结果
4. 使用`commands`模块(在Python 2中可用,在Python 3中已弃用):
```python
import commands
status, output = commands.getstatusoutput('ls')
print(output) 输出ls命令的结果
请注意,出于安全考虑,建议使用`subprocess`模块,因为它提供了更多的控制和选项,比如捕获输出、设置环境变量等。