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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何通过python [duplicate]在shell上运行命令相关的知识,希望对你有一定的参考价值。

可能重复: Calling an external command in Python

我想使用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管道或异步启动它),您可以使用subprocessmodule:

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 代码? [复制]

如何从 Flask App 执行 Shell 脚本 [重复]

如何让 python 脚本作为可执行文件运行? [复制]

如何将参数传递给 shell 脚本? [复制]

python Shell接口通过sh模块。

如何从 .sh 可执行文件执行远程 Python 文件?