欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python如何調(diào)用外部系統(tǒng)命令

 更新時(shí)間:2019年08月07日 09:44:54   作者:BengDou_Do&Think  
這篇文章主要介紹了Python如何調(diào)用外部系統(tǒng)命令,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

 前言

利用Python調(diào)用外部系統(tǒng)命令的方法可以提高編碼效率。調(diào)用外部系統(tǒng)命令完成后可以通過獲取命令執(zhí)行返回結(jié)果碼、執(zhí)行的輸出結(jié)果進(jìn)行進(jìn)一步的處理。本文主要描述Python常見的調(diào)用外部系統(tǒng)命令的方法,包括os.system()、os.popen()、subprocess.Popen()等。

本文分析python調(diào)用外部系統(tǒng)命令主要從兩個(gè)方面考慮:1、是不是可以返回命令執(zhí)行結(jié)果碼,因?yàn)榇蟛糠謭?chǎng)景都需要通過判斷調(diào)用命令是執(zhí)行成功還是失敗。2、是不是可以獲取命令執(zhí)行結(jié)果。某些場(chǎng)景調(diào)用外部命令就是為獲取輸出結(jié)果,也可以通過輸出結(jié)果來判斷命令執(zhí)行成功還是失敗。分析結(jié)果如下:

下面再針對(duì)每一個(gè)函數(shù)使用方法和實(shí)例進(jìn)行詳細(xì)描述。

1、subprocess模塊

優(yōu)先介紹subprocess模塊的是由于該模塊可以替代舊模塊的方法,如os.system()、os.popen()等,推薦使用。subporcess模塊可以調(diào)用外部系統(tǒng)命令來創(chuàng)建新子進(jìn)程,同時(shí)可以連接到子進(jìn)程的nput/output/error管道上,并得到子進(jìn)程的返回值。subprocess模塊主要有call()、check_call()、check_output()、Popen()函數(shù),簡要描述如下:

Main API
  ========
  call(...): Runs a command, waits for it to complete, then returns the return code.
  check_call(...): Same as call() but raises CalledProcessError() if return code is not 0
  check_output(...): Same as check_call() but returns the contents of stdout instead of a return code
  Popen(...): A class for flexibly executing a command in a new process
  
  Constants
  ---------
  PIPE:  Special value that indicates a pipe should be created
  STDOUT: Special value that indicates that stderr should go to stdout

下面開始介紹subprocess函數(shù)的使用方法。

(1)subprocess.Popen類

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)

參數(shù)說明:

args:
  要調(diào)用的外部系統(tǒng)命令。
 bufsize:
  默認(rèn)值為0, 表示不緩存,。為1表示行緩存,。其他正數(shù)表示緩存使用的大小,,負(fù)數(shù)-1表示使用系統(tǒng)默認(rèn)的緩存大小。
 stdin、stdout、stdout
  分別表示標(biāo)準(zhǔn)輸入、標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤。其值可以為PIPE、文件描述符和None等。默認(rèn)值為None,表示從父進(jìn)程繼承。
 shell
  Linux:參數(shù)值為False時(shí),Linux上通過調(diào)用os.execvp執(zhí)行對(duì)應(yīng)的程序。為Trule時(shí),Linux上直接調(diào)用系統(tǒng)shell來執(zhí)行程序。
  Windows:shell參數(shù)表示是否使用bat作為執(zhí)行環(huán)境。只有執(zhí)行windows的dir、copy等命令時(shí)才需要設(shè)置為True。其他程序沒有區(qū)別。
 executable
  用于指定可執(zhí)行程序。一般情況下我們通過args參數(shù)來設(shè)置所要運(yùn)行的程序。如果將參數(shù)shell設(shè)為 True,executable將指定程序使用的shell。在windows平臺(tái)下,默認(rèn)的shell由COMSPEC環(huán)境變量來指定。
 preexec_fn
  只在Unix平臺(tái)下有效,用于指定一個(gè)可執(zhí)行對(duì)象(callable object),它將在子進(jìn)程運(yùn)行之前被調(diào)用
 cwd
 設(shè)置子進(jìn)程當(dāng)前目錄
 env
  env是字典類型,用于指定子進(jìn)程的環(huán)境變量。默認(rèn)值為None,表示子進(jìn)程的環(huán)境變量將從父進(jìn)程中繼承。
 Universal_newlines
  不同操作系統(tǒng)下,文本的換行符是不一樣的。如:windows下用'/r/n'表示換,而Linux下用 ‘/n'。如果將此參數(shù)設(shè)置為True,Python統(tǒng)一把這些換行符當(dāng)作'/n'來處理。

Popen對(duì)象對(duì)應(yīng)的屬性和方法如下:

屬性:
 stdin, stdout, stderr, pid, returncode
方法:
 communicate(self, input=None) -> returns a tuple (stdout, stderr).
 wait(self) -> Wait for child process to terminate. Returns returncode attribute.

常用實(shí)例

1、打印D:\temp目錄下創(chuàng)建test目錄。直接調(diào)用進(jìn)程,不考慮獲取調(diào)用命令輸出內(nèi)容和結(jié)果碼

import subprocess
p = subprocess.Popen(args='mkdir test', shell=True, cwd='d:/temp')
p.wait()

2、調(diào)用ping命令執(zhí)行,獲取命令執(zhí)行輸出內(nèi)容

import subprocess
p = subprocess.Popen(args='ping -n 2 -w 3 192.168.1.104', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
p.wait()
print p.stdout.read()

說明:p.stdout、p.stdin、p.stderr為文件對(duì)象,可以使用文件對(duì)象函數(shù),如read()。

(2)subprocess.call()

函數(shù)原型:call(*popenargs, **kwargs)。call()調(diào)用外部系統(tǒng)命令執(zhí)行,并返回程序執(zhí)行結(jié)果碼。

import subprocess
retcode = subprocess.call('ping -n 2 -w 3 192.168.1.104', shell=True)
print retcode

(3)subprocess.check_call()

使用方法同call()。如果調(diào)用命令執(zhí)行成功,返回結(jié)果碼0,如果執(zhí)行失敗,拋出CalledProcessError.異常。舉例如下:

>>> p = subprocess.check_call('ping -n 2 -w 3 192.168.1.105', shell=True)
正在 Ping 192.168.1.105 具有 32 字節(jié)的數(shù)據(jù):
請(qǐng)求超時(shí)。
請(qǐng)求超時(shí)。
192.168.1.105 的 Ping 統(tǒng)計(jì)信息:
  數(shù)據(jù)包: 已發(fā)送 = 2,已接收 = 0,丟失 = 2 (100% 丟失),
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "c:\Python27\lib\subprocess.py", line 186, in check_call
  raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'ping -n 2 -w 3 192.168.1.105' returned non-zero exit status 1

(4)subprocess.check_output()

函數(shù)原型:check_output(*popenargs, **kwargs)。用法與call()相同。區(qū)別是如果執(zhí)行成功返回的是標(biāo)準(zhǔn)輸出內(nèi)容。如果失敗,拋CalledProcessError.異常。

import subprocess
output = subprocess.check_output('ping -n 2 -w 3 192.168.1.104', shell=True)
print output

2、os模塊

(1)os.system()

os.system(command) 。調(diào)用外部系統(tǒng)命令,返回命令結(jié)果碼,但是無法獲取命令執(zhí)行輸出結(jié)果,輸出結(jié)果直接打印到屏幕終端。

import os
retcode = os.system('ping -n 2 -w 3 192.168.1.104')
if retcode == 0:
  print "%s Success" % (ip,)
else:
  print "%s Fail" % (ip,)

(2)os.popen()

os.popen(command) 。調(diào)用外部系統(tǒng)命令,返回命令執(zhí)行輸出結(jié)果,但不返回結(jié)果嗎

import os
output = os.popen('ping -n 2 -w 3 192.168.1.104')
print output

3、commands模塊

commands模塊用于調(diào)用Linux shell命令。測(cè)試了下在windows上執(zhí)行失敗。主要有如下3個(gè)函數(shù)

getoutput(cmd): Return output (stdout or stderr) of executing cmd in a shell.
getstatus(file):Return output of "ls -ld <file>" in a string.
getstatusoutput(cmd):Return (status, output) of executing cmd in a shell

使用實(shí)例如下:

import commands
retcode, output = commands.getstatusoutput('ping -n 2 -w 3 192.168.1.104')
print retcode
print output

總結(jié)

在編寫程序時(shí)可根據(jù)使用場(chǎng)景來選擇不同的Python調(diào)用方法來執(zhí)行外部系統(tǒng)命令。對(duì)于復(fù)雜的命令考慮使用subprocess.Popen()完成,如果僅是簡單的命令執(zhí)行,可以使用os.system()完成,如調(diào)用windows的暫停程序命令os.system('pause')。

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論