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

mru*_*jay 12 python subprocess

可能重复:
在Python中调用外部命令

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

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

我想做的是如下,

cd dir1
execute some commands
return 
cd dir2
execute some commands
Run Code Online (Sandbox Code Playgroud)

Nli*_*tis 5

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

import os
os.system('touch myfile')
Run Code Online (Sandbox Code Playgroud)

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

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


Gjo*_*dis 1

os.system("/dir/to/executeble/COMMAND")
Run Code Online (Sandbox Code Playgroud)

例如

os.system("/usr/bin/ping www.google.com")
Run Code Online (Sandbox Code Playgroud)

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

当然你需要导入 os 模块。

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

subprocess.call 或类似的东西