使用Python执行shell命令

时间:2020-03-05 15:26:41  来源:igfitidea点击:

Python是一个很好的脚本语言。
越来越多的Sysadmins正在使用Python脚本来自动化他们的工作。

由于Sysadmin任务一直涉及Linux命令,因此从Python脚本运行Linux命令是一个很大的帮助。

在本教程中,将介绍几种方法可以运行shell命令并在Python程序中获取其输出。

使用OS模块执行Python中的shell命令

让我创建一个简单的python程序,它使用操作系统模块执行shell命令。

import os
myCmd = 'ls -la'
os.system(myCmd)

现在,如果我运行这个程序,这就是我在输出中看到的。

python prog.py 
total 40
drwxr-xr-x  3 igi igi 4096 Jan 17 15:58 .
drwxr-xr-x 49 igi igi 4096 Jan 17 15:05 ..
-r--r--r--  1 igi igi  456 Dec 11 21:29 agatha.txt
-rw-r--r--  1 igi igi    0 Jan 17 12:11 count
-rw-r--r--  1 igi igi   14 Jan 10 16:12 count1.txt
-rw-r--r--  1 igi igi   14 Jan 10 16:12 count2.txt
--w-r--r--  1 igi igi  356 Jan 17 12:10 file1.txt
-rw-r--r--  1 igi igi  356 Dec 17 09:59 file2.txt
-rw-r--r--  1 igi igi   44 Jan 17 15:58 prog.py
-rw-r--r--  1 igi igi  356 Dec 11 21:35 sherlock.txt
drwxr-xr-x  3 igi igi 4096 Jan  4 20:10 target

这是Prog.py存储的目录的内容。

如果要使用shell命令的输出,可以直接从shell命令将其存储在文件中:

import os
myCmd = 'ls -la > out.txt'
os.system(myCmd)

我们还可以通过这种方式将shell命令的输出存储在变量中:

import os
myCmd = os.popen('ls -la').read()
print(myCmd)

如果运行上述程序,它将打印变量MyCMD的内容,并且它将与我们之前看到的LS命令的输出相同。

现在让我们看看在Python中运行Linux命令的另一种方法。

使用子过程模块执行Python中的shell命令

在Python中运行shell命令的稍微更好的方法使用子过程模块。

如果要在没有任何选项和参数的情况下运行shell命令,则可以调用这样的子过程:

import subprocess
subprocess.call("ls")

调用方法将执行shell命令。
运行程序时,我们将看到当前工作目录的内容:

python prog.py 
agatha.txt  count1.txt    file1.txt  prog.py   target
count        count2.txt  file2.txt  sherlock.txt

如果要与shell命令一起提供选项和参数,则必须在列表中提供它们。

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

运行程序时,我们将看到列表格式中当前目录的内容。

既然我们知道如何使用子处理运行shell命令,问题出现了存储shell命令的输出。

为此,我们必须使用popen函数。
它输出到Popen对象,该对象具有可用于将标准输出和误差作为元组的标准输出和错误。

我们可以在此处了解有关Subprocess模块的更多信息。

import subprocess
MyOut = subprocess.Popen(['ls', '-l', '.'], 
            stdout=subprocess.PIPE, 
            stderr=subprocess.STDOUT)
stdout,stderr = MyOut.communicate()
print(stdout)
print(stderr)

运行程序时,我们将看到stdout和stderr(在这种情况下为止)。

python prog.py 
 total 32
 -r--r--r-- 1 igi igi  456 Dec 11 21:29 agatha.txt
 -rw-r--r-- 1 igi igi    0 Jan 17 12:11 count
 -rw-r--r-- 1 igi igi   14 Jan 10 16:12 count1.txt
 -rw-r--r-- 1 igi igi   14 Jan 10 16:12 count2.txt
 --w-r--r-- 1 igi igi  356 Jan 17 12:10 file1.txt
 -rw-r--r-- 1 igi igi  356 Dec 17 09:59 file2.txt
 -rw-r--r-- 1 igi igi  212 Jan 17 16:54 prog.py
 -rw-r--r-- 1 igi igi  356 Dec 11 21:35 sherlock.txt
 drwxr-xr-x 3 igi igi 4096 Jan  4 20:10 target
None