subprocess報錯FileNotFoundError: [WinError 2] 系統找不到指定的文件

0x00 環境

名稱
OS系統 windows 7 64bit
編程語言 python 3.7

0x01 問題

使用subprocess.Popen執行命令報錯,錯誤信息如下:

Traceback (most recent call last):
  File "xxx.py", line 4, in addLabel
    output = Popen('dir',stdout=PIPE)
  File "D:\Program Files\Python3\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "D:\Program Files\Python3\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] 系統找不到指定的文件。

源碼如下

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE
output = Popen('dir',stdout=PIPE)

0x02 原因

dir 命令是cmd.exe 或者powershell.exe才能理解的命令。在Windows環境下subprocess.Popen默認是不會調用cmd.exe的。所以需要指定。

subprocess.Popen(["cmd", "/c", "dir", "c:\\Users"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

0x03 參考鏈接

https://stackoverflow.com/questions/49018413/filenotfounderror-subprocess-popendir-windows-7

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章