分享

Python:如何运行外部的linux/unix命令/程序

 panhoy 2014-05-29

我们在写python程序的时候,有时候需要调用现成的外部命令或者已经编译好的外部程序, 那么在python里如何调用呢?

下面来介绍一个python的模块:subprocess. 这个模块可以创建一个新的进程,并可以获取到该进程的标准输入/输出以及标准的错误输出, 而且可以该进程最后的返回值。当然python里还有其它的模块可以实现这种需求,比如:os.system, os.spawn*, os.popen*.

python subprocess模块的用法

  1. import subprocess
  2. subprocess.call("命令“)
  3. subprocess.call(["命令”,“参数”])

英文文档

https://docs./2/library/subprocess.html

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

Run the command described by args. Wait for command to complete, then return the returncode attribute.

Popen Constructor

The underlying process creation and management in this module is handled by the Popen class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions.

class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)

Execute a child program in a new process. On Unix, the class uses os.execvp()-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function. The arguments to Popen are as follows.

args should be a sequence of program arguments or else a single string. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence.

On Unix, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program.

Note

shlex.split() can be useful when determining the correct tokenization for args, especially in complex cases:

>>>
>>> import shlex, subprocess
>>> command_line = raw_input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print args
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!

Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements.

On Windows, if args is a sequence, it will be converted to a string in a manner described in Converting an argument sequence to a string on Windows. This is because the underlying CreateProcess() operates on strings.

The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.

On Unix with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, Popen does the equivalent of:





python程序中执行ifconfig命令去获取系统网卡的信息

  1. #!/usr/bin/python
  2. import subprocess
  3. subprocess.call("ifconfig")

程序执行后输出如下:

  1. eth0 Link encap:Ethernet HWaddr
  2. inet addr:10.10.10.200 Bcast:10.10.10.255 Mask:255.255.255.0
  3. UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
  4. RX packets:62621520 errors:0 dropped:0 overruns:0 frame:0
  5. TX packets:43688 errors:0 dropped:0 overruns:0 carrier:0
  6. collisions:0 txqueuelen:1000
  7. RX bytes:2787090014 (2.5 GiB) TX bytes:1835004 (1.7 MiB)
  8. Interrupt:164

python程序调用netstat -l命令查看正在监听的端口

  1. #!/usr/bin/python
  2. import subprocess
  3. subprocess.call(["netstat","-l"])

程序执行后输出如下:

  1. Active Internet connections (only servers)
  2. Proto Recv-Q Send-Q Local Address Foreign Address State
  3. tcp 0 0 *:mysql *:* LISTEN
  4. tcp 0 0 *:http *:* LISTEN
  5. tcp 0 0 *:ftp *:* LISTEN
  6. tcp 0 0 *:ssh *:* LISTEN
  7. tcp 0 0 *:ssh *:* LISTEN

如何将外部命令的输出传给python的一个变量呢?我们可以使用subprocess中的Popen类来实现

  1. #!/usr/bin/python
  2. import subprocess
  3.  
  4. Temp=subprocess.Popen(["netstat","-l"], stdout=subprocess.PIPE, shell=True)
  5. (output,errput)=Temp.communicate()
  6. return_value=Temp.wait()
  7. print "命令输出:“,output
  8. print "命令退出状态:“, return_value

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多