-
Notifications
You must be signed in to change notification settings - Fork 0
[系統互動篇] 如何呼叫系統指令,並讀取結果
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
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
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'))
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()
tj_tsai / tsungjung411@yahoo.com.tw / tsungjung411@gmail.com