python能在linux运行么_Python:如何运行外部的linux/unix命令/程序

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

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

python subprocess模块的用法

importsubprocess

subprocess.call("命令“)

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, 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.

classsubprocess.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命令去获取系统网卡的信息

#!/usr/bin/python

importsubprocess

subprocess.call("ifconfig")

程序执行后输出如下:

eth0Linkencap:EthernetHWaddr

inet addr:10.10.10.200Bcast:10.10.10.255Mask:255.255.255.0

UP BROADCAST RUNNING MULTICAST MTU:1500Metric:1

RX packets:62621520errors:0dropped:0overruns:0frame:0

TX packets:43688errors:0dropped:0overruns:0carrier:0

collisions:0txqueuelen:1000

RX bytes:2787090014(2.5GiB)TX bytes:1835004(1.7MiB)

Interrupt:164

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

#!/usr/bin/python

importsubprocess

subprocess.call(["netstat","-l"])

程序执行后输出如下:

ActiveInternetconnections(only servers)

ProtoRecv-QSend-QLocalAddressForeignAddressState

tcp00*:mysql*:*LISTEN

tcp00*:http*:*LISTEN

tcp00*:ftp*:*LISTEN

tcp00*:ssh*:*LISTEN

tcp00*:ssh*:*LISTEN

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

#!/usr/bin/python

importsubprocess

Temp=subprocess.Popen(["netstat","-l"],stdout=subprocess.PIPE,shell=True)

(output,errput)=Temp.communicate()

return_value=Temp.wait()

print"命令输出:“,output

print "命令退出状态:“,return_value

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值