在Python中执行命令,你可以使用以下几种方法:
1. 使用`os.system`
import os
os.system('ls -l /tmp/')
2. 使用`subprocess`模块
import subprocess
subprocess.call(['ls', '-l', '/tmp/'])
3. 使用`os.popen`
import os
with os.popen('ls -l /tmp/') as pipe:
output = pipe.read()
print(output)
4. 使用`subprocess.Popen`
import subprocess
with subprocess.Popen(['ls', '-l', '/tmp/'], stdout=subprocess.PIPE) as proc:
output, _ = proc.communicate()
print(output.decode('utf-8'))
5. 使用`subprocess.run`(Python 3.5+)
import subprocess
result = subprocess.run(['ls', '-l', '/tmp/'], capture_output=True, text=True)
print(result.stdout)
请根据你的需求选择合适的方法。如果你需要非阻塞执行命令,并且希望Python脚本结束后,命令仍然继续执行,你可能需要使用`&`符号将命令放入后台运行,或者在Python脚本中启动这些命令,然后退出。