无法使用子进程运行Windows命令,Popen

f87krz0w  于 2022-11-30  发布在  Windows
关注(0)|答案(1)|浏览(253)

我试图运行一个简单的windows命令dir E:\Projects\ML /s /b使用subprocess.Popen函数而不使用Shell=True,我的示例程序如下

import subprocess
import os
import time

input='E:\Projects\ML'
command = "dir "+input+' /s /b '
os.system(command)
status=subprocess.Popen(command.split(' '),shell=False,text=True,cwd=input,stdout=subprocess.PIPE)
while status.wait()!=0:
    time.sleep(1)
print(status.communicate())

对于os.system(),该命令给出了适当的结果,但对于Popen(),我遇到了以下问题

Traceback (most recent call last):
  File "e:\Projects\ArchiveViewer\PythonR&D\EncriptionWithPopen\runLocalCMD.py", line 9, in <module>
    status=subprocess.Popen(command.split(' '),shell=False,text=True,cwd=input,stdout=subprocess.PIPE)
  File "C:\Users\nmaiya\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\nmaiya\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1420, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

我知道如果设置shell=True,该命令将运行,但是否有任何原因导致它无法与shell=Fales一起运行

zf9nrax1

zf9nrax11#

dir是cmd.exe中的内部命令,没有可以作为进程启动的dir.exe。
system("xyz")在Windows上内部执行类似于cmd.exe /C xyz

相关问题