如何通过python [duplicate]在shell上运行命令
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何通过python [duplicate]在shell上运行命令相关的知识,希望对你有一定的参考价值。
我想使用python在另一个目录中运行命令。
用于此的各种方法有哪些,哪种方式最有效?
我想做的是如下,
cd dir1
execute some commands
return
cd dir2
execute some commands
答案
当然如果你只想通过python在shell上运行(简单)命令,你可以通过system
模块的os
函数来完成。例如:
import os
os.system('touch myfile')
如果您想要更复杂的东西,以便更好地控制命令的执行,请继续使用其他人建议的subprocess
模块。
有关详细信息,请访问以下链接:
另一答案
如果您想要更多地控制被调用的shell命令(即访问stdin和/或stdout管道或异步启动它),您可以使用subprocess
module:
import subprocess
p = subprocess.Popen('ls -al', shell=True, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
另见subprocess
module documentation。
另一答案
os.system("/dir/to/executeble/COMMAND")
例如
os.system("/usr/bin/ping www.google.com")
如果ping程序位于“/ usr / bin”
当然你需要导入os模块。
os.system不等待任何输出,如果你想要输出,你应该使用
subprocess.call或类似的东西
另一答案
您可以使用Python Subprocess,它提供许多模块来执行命令,检查输出和接收错误消息等。
以上是关于如何通过python [duplicate]在shell上运行命令的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Linux 终端上运行带有输入的 python 代码? [复制]