如何通过python在shell上运行命令 [英] How to run commands on shell through python

查看:50
本文介绍了如何通过python在shell上运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I want to run commands in another directory using python.

为此使用的各种方法有哪些,哪种方法最有效?

What are the various ways used for this and which is the most efficient one?

我想做的如下,

cd dir1
execute some commands
return 
cd dir2
execute some commands

推荐答案

当然如果你只想通过 python 在 shell 上运行一个(简单的)命令,你可以通过 systemos 模块.例如:

Naturally if you only want to run a (simple) command on the shell via python, you do it via the system function of the os module. For instance:

import os
os.system('touch myfile')

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

If you would want something more sophisticated that allows for even greater control over the execution of the command, go ahead and use the subprocess module that others here have suggested.

有关更多信息,请访问以下链接:

For further information, follow these links:

  • Python official documentation on os.system()
  • Python official documentation on the subprocess module

这篇关于如何通过python在shell上运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆