Python執行Linux系統命令的4種方法

2021-08-29 18:50:38 字數 2539 閱讀 8845

(1) os.system

僅僅在乙個子終端執行系統命令,而不能獲取命令執行後的返回資訊

複製****如下:

system(command) -> exit_status 

execute the command (a string) in a subshell.

如果再命令列下執行,結果直接列印出來

複製****如下:

>>> os.system('ls')

04101419778.chm   bash      document    media      py-django   video

11.wmv            books     downloads   pictures  python

all-20061022      desktop   examples    project    tools

(2) os.popen

該方法不但執行命令還返回執行後的資訊物件

複製****如下:

popen(command [, mode='r' [, bufsize]]) -> pipe 

open a pipe to/from a command returning a file object.

例如:複製****如下:

>>>tmp = os.popen('ls *.py').readlines()

>>>tmp

out[21]:

['dump_db_pickle.py ',

'dump_db_pickle_recs.py ',

'dump_db_shelve.py ',

'initdata.py ',

'__init__.py ',

'make_db_pickle.py ',

'make_db_pickle_recs.py ',

'make_db_shelve.py ',

'peopleinteract_query.py ',

'reader.py ',

'testargv.py ',

'teststreams.py ',

'update_db_pickle.py ',

'writer.py ']

好處在於:將返回的結果賦於一變數,便於程式的處理。

(3)  使用模組 subprocess

複製****如下:

>>> import subprocess

>>> subprocess.call(["cmd", "arg1", "arg2"],shell=true)

from subprocess import call

call(['python3','-m','nbconvert','assessing.ipynb']) ## output,若成功,返回**0,失敗則返回大於0的數字 0

獲取返回和輸出:

複製****如下:

import subprocess

p = subprocess.popen('ls', shell=true, stdout=subprocess.pipe, stderr=subprocess.stdout)

for line in p.stdout.readlines():

print line,

retval = p.wait()

(4)  使用模組 commands

複製****如下:

>>> import commands

>>> dir(commands)

['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput', 'getstatus','getstatusoutput', 'mk2arg', 'mkarg']

>>> commands.getoutput("date")

'wed jun 10 19:39:57 cst 2009'

>>>

>>> commands.getstatusoutput("date")

(0, 'wed jun 10 19:40:41 cst 2009')

注意: 當執行命令的引數或者返回中包含了中文文字,那麼建議使用subprocess,如果使用os.popen則會出現下面的錯誤:

複製****如下:

traceback (most recent call last):

file "./test1.py", line 56, inmain()

file "./test1.py", line 45, in main

fax.sendfax()

file "./mailfax/fax.py", line 13, in sendfax

os.popen(cmd)

unicodeencodeerror: 'ascii' codec can't encode characters in position 46-52: ordinal not inrange(128)

Linux系統後台執行python指令碼

ps ef grep pythonps是linux下最常用的也是非常強大的程序檢視命令 grep命令是查詢,是一種強大的文字搜尋工具,它能使用正規表示式搜尋文字,並把匹配的行列印出來 grep全稱是global regular expression print,表示全域性正規表示式版本,它的使用許可...

Linux系統中執行python檔案

linux系統和linux伺服器中都是適用的 linux下可直接像執行.exe檔案一樣執行.py檔案,方法是在.py檔案的第一行加上下面的任意一行 usr bin python usr bin env python二者的區別在於 需要強調的是,上述解析路徑應該放在 python 指令碼的第一行。做完...

Python執行LINUX系統指令的方法

1 os.system 僅僅在乙個子終端執行系統命令,而不能獲取命令執行後的返回資訊 複製 如下 system command exit status execute the command a string in a subshell.如果再命令列下執行,結果直接列印出來 例如 如下 os.sys...