python呼叫shell命令 批量執行python程式
阿新 • • 發佈:2021-01-06
一、問題背景
學生寫了一個計算器程式test.py,我要去測上面這個5個命令是否能夠獲得正確的結果
我想寫一個python程式碼,包含上面5個命令,並輸出給我看結果,可以實現嗎?
二、不需要獲取shell返回結果的
使用
os.system(command)
新建judge.py
# -*- coding: utf-8 -*- import os os.system("python3 test.py \"1 + 2 - 3 + 4\"") os.system("python3 test.py \"1 + 2 - 3 + 1 / 3\"") os.system("python3 test.py \"1 + + 2\"") os.system("python3 test.py \"1 / 0\"") os.system("python3 test.py \"a + 1\"")
三、需要獲取返回結果的
我不想用眼睛比較結果是否正確,想讓程式碼自動比較結果是否正確。
但是os.system返回值: 0、1、-1等int的數字.
可以使用
subprocess.Popen("command", stdout=subprocess.PIPE, shell=True).stdout.readlines()
# -*- coding: utf-8 -*- import os import subprocess resp = subprocess.Popen("python3 test.py \"1 + 2 - 3 + 4\"", stdout=subprocess.PIPE, shell=True).stdout.readlines() print(resp) os.system("python3 test.py \"1 + 2 - 3 + 4\"") os.system("python3 test.py \"1 + 2 - 3 + 1 / 3\"") os.system("python3 test.py \"1 + + 2\"") os.system("python3 test.py \"1 / 0\"") os.system("python3 test.py \"a + 1\"")
可以再寫幾行程式碼提取一下