Python脚本在终端中执行命令

时间:2010-09-16 21:28:28

标签: python terminal

我刚才在某个地方看过这个,但似乎无法找到它。我试图找到一个命令,它将在终端中执行命令,然后输出结果。

例如:脚本将是:

command 'ls -l'

它将终止在终端中运行该命令的结果

10 个答案:

答案 0 :(得分:133)

有几种方法可以做到这一点:

一种简单的方法是使用os模块:

import os
os.system("ls -l")

使用子进程模块可以实现更复杂的事情: 例如:

import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]

答案 1 :(得分:20)

我更喜欢使用子进程模块:

Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("ka-GE"); // Georgia culture code. I'm not sure this is correct.

原因是,如果你想在脚本中传递一些变量,这可以很容易地获取代码的以下部分

from subprocess import call
call(["ls", "-l"])

答案 2 :(得分:6)

事实上,关于子流程的任何问题都是一个很好的阅读

答案 3 :(得分:2)

您还应该查看commands.getstatusoutput

这会返回一个长度为2的元组。 第一个是返回整数(0 - 命令成功时) 第二个是终端显示的整个输出。

对于ls

    import commands
    s=commands.getstatusoutput('ls')
    print s
    >> (0, 'file_1\nfile_2\nfile_3')
    s[1].split("\n")
    >> ['file_1', 'file_2', 'file_3']

答案 4 :(得分:1)

os.popen()非常简单易用,但自Python 2.6以来已被弃用。 您应该使用子进程模块。

请在此处阅读:reading a os.popen(command) into a string

答案 5 :(得分:1)

import os
os.system("echo 'hello world'")

这应该有效。我不知道如何将输出打印到python Shell中。

答案 6 :(得分:1)

Jupyter

在jupyter笔记本中,您可以使用魔术功能!

!echo "execute a command"
files = !ls -a /data/dir/ #get the output into a variable

ipython

要将其作为.py脚本执行,您需要使用ipython

files = get_ipython().getoutput('ls -a /data/dir/')

执行脚本

$ ipython my_script.py

答案 7 :(得分:1)

在 python3 中,标准方法是使用 subprocess.run

res = subprocess.run(['ls', '-l'], capture_output=True)
print(res.stdout)

答案 8 :(得分:0)

您可以导入“ os”模块并像这样使用它:

import os
os.system('#DesiredAction')

答案 9 :(得分:0)

对于python3使用子进程

import subprocess
s = subprocess.getstatusoutput(f'ps -ef | grep python3')
print(s)