當(dāng)我們?cè)趯?xiě)python程序的時(shí)候,有時(shí)候需要調(diào)用現(xiàn)成的外部命令或者已經(jīng)編譯好的外部程序, 那么在python里如何調(diào)用呢?
下面來(lái)介紹一個(gè)python的模塊:subprocess. 這個(gè)模塊可以創(chuàng)建一個(gè)新的進(jìn)程,并可以獲取到該進(jìn)程的標(biāo)準(zhǔn)輸入/輸出以及標(biāo)準(zhǔn)的錯(cuò)誤輸出, 而且可以該進(jìn)程最后的返回值。當(dāng)然python里還有其它的模塊可以實(shí)現(xiàn)這種需求,比如:os.system, os.spawn*, os.popen*.
python subprocess模塊的用法
- import subprocess
- subprocess.call("命令“)
- subprocess.call(["命令”,“參數(shù)”])
英文文檔 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程序中執(zhí)行ifconfig命令去獲取系統(tǒng)網(wǎng)卡的信息
- #!/usr/bin/python
- import subprocess
- subprocess.call("ifconfig")
程序執(zhí)行后輸出如下:
- eth0 Link encap:Ethernet HWaddr
- inet addr:10.10.10.200 Bcast:10.10.10.255 Mask:255.255.255.0
- UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
- RX packets:62621520 errors:0 dropped:0 overruns:0 frame:0
- TX packets:43688 errors:0 dropped:0 overruns:0 carrier:0
- collisions:0 txqueuelen:1000
- RX bytes:2787090014 (2.5 GiB) TX bytes:1835004 (1.7 MiB)
- Interrupt:164
python程序調(diào)用netstat -l命令查看正在監(jiān)聽(tīng)的端口
- #!/usr/bin/python
- import subprocess
- subprocess.call(["netstat","-l"])
程序執(zhí)行后輸出如下:
- Active Internet connections (only servers)
- Proto Recv-Q Send-Q Local Address Foreign Address State
- tcp 0 0 *:mysql *:* LISTEN
- tcp 0 0 *:http *:* LISTEN
- tcp 0 0 *:ftp *:* LISTEN
- tcp 0 0 *:ssh *:* LISTEN
- tcp 0 0 *:ssh *:* LISTEN
如何將外部命令的輸出傳給python的一個(gè)變量呢?我們可以使用subprocess中的Popen類來(lái)實(shí)現(xiàn)
- #!/usr/bin/python
- import subprocess
-
- Temp=subprocess.Popen(["netstat","-l"], stdout=subprocess.PIPE, shell=True)
- (output,errput)=Temp.communicate()
- return_value=Temp.wait()
- print "命令輸出:“,output
- print "命令退出狀態(tài):“, return_value
|