Skip to content

[系統互動篇] 如何呼叫系統指令,並讀取結果

Tsung-Jung Tsai (TJ_Tsai) edited this page Sep 23, 2022 · 3 revisions

無法擷取執行內容

import os
exited_code = os.system('pwd')
print('exited_code:', exited_code)

import subprocess
exited_code = subprocess.call('pwd')
print('exited_code:', exited_code)

執行結果(在python notebook):

exited_code: 0
exited_code: 0

執行結果(在python terminal):

/home/tj/Downloads/test
exited_code: 0
/home/tj/Downloads/test
exited_code: 0

擷取執行內容

範例1

import subprocess
print(subprocess.check_output('ls -ls', shell=True).decode('utf-8'))

執行結果:

total 4
4 -rw-r--r-- 1 tj tj 125  一  13 11:47 main.py

範例2

import subprocess
process = subprocess.run('ls -ls', shell=True, capture_output=True)
print(process.stdout.decode('utf-8'))
import subprocess
process = subprocess.run(['ls', '-ls'], shell=False, capture_output=True)
print(process.stdout.decode('utf-8'))

範例3

import subprocess
cmd = 'date; sleep 2; date; exit 1'
process = subprocess.run(cmd, shell=True, capture_output=True)
print(process.stdout.decode('utf-8'))
process.check_returncode()

image

Clone this wiki locally