1. 程式人生 > >python3基礎07(程序操作及執行系統級命令等)

python3基礎07(程序操作及執行系統級命令等)

#subprocess 建立子程序 連線輸入 輸出 管道錯誤,及獲取他們的狀態,可執行作業系統級的命令
# subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False,
# cwd=None, timeout=None, check=False, encoding=None, errors=None, env=None)

stdin stdout stderr 檔案描述符 或物件 subprocess.PIPE subprocess.DEVNULL None
encoding預設位元組,可設定編碼
shell為True,通過shell執行的命令
args為字串,必須指定shell=True
args為字串列表,不用指定shell,預設shell=False
args為字串列表,指定shell=True時,引數被忽略

#返回的是CompletedProcess物件
args 程序的引數
returncode 狀態碼
stdout 輸出資訊 為bytes,需要通過decdoe編碼才正常顯示字串
stderr 錯誤資訊
check_returncode 返回碼


ret = subprocess.run(['ipconfig', '/all'],stdout=subprocess.PIPE)
result=bytes(ret.stdout).decode(encoding='gbk')
print(result)

print(sys.builtin_module_names)
print(sys.modules)
ret = subprocess.run(['ipconfig', '/all'], shell=True)


s = subprocess.Popen("python", stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)
s.stdin.write(b"import os\n")
s.stdin.write(b"print(os.environ)")
s.stdin.close()

out = s.stdout.read().decode("GBK")
s.stdout.close()
print(out)