Python 系統命令呼叫之 subprocess

2021-10-03 17:34:24 字數 1722 閱讀 7929

python 3不再推薦使用老的os.system()、os.popen()、commands.getstatusoutput()等方法來呼叫系統命令,而建議統一使用subprocess庫所對應的方法如:popen()、getstatusoutput()、call()。

# 標準用法使用資料傳參,可以用shlex庫來正確切割命令字串

>>> import shlex, subprocess

>>> command_line = 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!

import subprocess

try:

proc = subprocess.popen([`ls`, `-a`, `/`], stdout=subprocess.pipe)

print(proc.stdout.read())

except:

print("error when run `ls` command")

# 使用with語句替代try-except-finally

with popen(["ifconfig"], stdout=pipe) as proc:

log.write(proc.stdout.read())

# windows下由於windows api的createprocess()入參為字串,

# popen需要把輸入的陣列拼接為字串。因此建議直接傳入字串引數。

p = subprocess.popen('d:\\tools\\git\\git-bash.exe --cd="d:\\codes"', stdout=subprocess.pipe)

print(p.stdout.read())

import subprocess

try:

retcode = subprocess.call("mycmd" + " myarg", shell=true)

if retcode < 0:

print("child was terminated by signal", -retcode, file=sys.stderr)

else:

print("child returned", retcode, file=sys.stderr)

except oserror as e:

print("execution failed:", e, file=sys.stderr)

>>> subprocess.getstatusoutput('ls /bin/ls')

(0, '/bin/ls')

>>> subprocess.getoutput('ls /bin/ls')

'/bin/ls'

詳細可以查閱python 3官方文件:

系統呼叫之lseek

注意 這個指標是和檔案描述符相掛鉤的,並不與這個檔案掛鉤,所以可以有多個程序來對這個檔案進行操作,不會影響各自。當從檔案讀取資料時,核心從指標指向的位置開始,讀取指定的位元組數,然後移動指標,指向下乙個未被讀取過的位元組,寫檔案的過程也是類似。off t oldpos lseek int fd,of...

python 呼叫系統命令

使用 os.system 呼叫系統命令 程式中無法獲得到輸出和返回值 import os os.system ls l proc cpuinfo os.system ls l proc cpuinfo r r r 1 root root 0 3月 29 16 53 proc cpuinfo 0使用 ...

python呼叫系統命令

1.os.system 例如 os.system ls 如果在命令列下執行,結果直接列印出來 裡面的引數即為dos命令。這樣的話是不能將得到的東西顯示出來的。但是如果是執行一些其他的操作dos操作的話應該可以實現的。2.為了能夠得到返回的結果集可以這樣來處理的 os.popen popen comm...