打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

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

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

python subprocess模块的用法

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

英文文档

https://docs.python.org/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, thenreturn the returncode attribute.

Popen Constructor

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

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 usesos.execvp()-like behavior to execute the child program. On Windows,the class uses the Windows CreateProcess() function. The arguments toPopen 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 isa sequence. If args is a string, the interpretation isplatform-dependent and described below. See the shell and executablearguments for additional differences from the default behavior. Unlessotherwise stated, it is recommended to pass args as a sequence.

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

Note

shlex.split() can be useful when determining the correcttokenization 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 (suchas eggs.txt) that are separated by whitespace in the shell go in separatelist elements, while arguments that need quoting or backslash escaping whenused in the shell (such as filenames containing spaces or the echo commandshown above) are single list elements.

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

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

On Unix with shell=True, the shell defaults to /bin/sh. Ifargs is a string, the string specifies the commandto execute through the shell. This means that the string must beformatted exactly as it would be when typed at the shell prompt. Thisincludes, for example, quoting or backslash escaping filenames with spaces inthem. If args is a sequence, the first item specifies the command string, andany additional items will be treated as additional arguments to the shellitself. 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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python 执行 shell 命令
Python模块学习
python笔记65 - Python3 subprocess执行命令行获取返回结果
sublime3插件开发
Python subprocess调用额外命令
Python subprocess模块call&check_call
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服