日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

Python:如何運(yùn)行外部的linux/unix命令/程序

 panhoy 2014-05-29

當(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模塊的用法

  1. import subprocess
  2. subprocess.call("命令“)
  3. 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)卡的信息

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

程序執(zhí)行后輸出如下:

  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程序調(diào)用netstat -l命令查看正在監(jiān)聽(tīng)的端口

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

程序執(zhí)行后輸出如下:

  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的一個(gè)變量呢?我們可以使用subprocess中的Popen類來(lái)實(shí)現(xiàn)

  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 "命令退出狀態(tài):“, return_value

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多