如何通过python [duplicate]在shell上运行命令

问题描述 投票:12回答:4

可能重复: Calling an external command in Python

我想使用python在另一个目录中运行命令。

用于此的各种方法有哪些,哪种方式最有效?

我想做的是如下,

cd dir1
execute some commands
return 
cd dir2
execute some commands
python subprocess
4个回答
5
投票

当然如果你只想通过python在shell上运行(简单)命令,你可以通过system模块的os函数来完成。例如:

import os
os.system('touch myfile')

如果您想要更复杂的东西,以便更好地控制命令的执行,请继续使用其他人建议的subprocess模块。

有关详细信息,请访问以下链接:


3
投票

如果您想要更多地控制被调用的shell命令(即访问stdin和/或stdout管道或异步启动它),您可以使用subprocessmodule:

import subprocess

p = subprocess.Popen('ls -al', shell=True, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()

另见subprocess module documentation


1
投票
os.system("/dir/to/executeble/COMMAND")

例如

os.system("/usr/bin/ping www.google.com")

如果ping程序位于“/ usr / bin”

当然你需要导入os模块。

os.system不等待任何输出,如果你想要输出,你应该使用

subprocess.call或类似的东西


0
投票

您可以使用Python Subprocess,它提供许多模块来执行命令,检查输出和接收错误消息等。

© www.soinside.com 2019 - 2024. All rights reserved.