windows 用子进程包装 cmd.exe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2028207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:43:08  来源:igfitidea点击:

wrapping cmd.exe with subprocess

pythonwindowssubprocess

提问by user246456

I try to wrap cmd.exe under windows with the following program but it doesn't work , it seems to wait for something and doesn't display anything. Any idea what is wrong here ?

我尝试使用以下程序将 cmd.exe 包装在 windows 下,但它不起作用,它似乎在等待某些东西并且不显示任何内容。知道这里有什么问题吗?

import subprocess

process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)  
process.stdin.write("dir\r\n")  
output = process.stdout.readlines()  
print output

采纳答案by interjay

This locks up because process.stdout.readlines()reads all output by the process (until it terminates). Since cmd.exe is still running, it keeps waiting forever for it to close.

这会锁定,因为process.stdout.readlines()读取进程的所有输出(直到它终止)。由于 cmd.exe 仍在运行,它会一直等待它关闭。

To fix this, you can start a separate thread to read the process output. This is something you need to do anyway if you don't call communicate(), to avoid possible deadlock. This thread can call process.stdout.readline()repeatedly and handle the data or send it back to the main thread for handling.

要解决此问题,您可以启动一个单独的线程来读取进程输出。如果您不调用communicate(),则无论如何都需要这样做,以避免可能的死锁。该线程可以process.stdout.readline()重复调用并处理数据或将其发送回主线程进行处理。

回答by Brian

Usually when trying to call command prompt with an actual command, it is simpler to just call it with the "/k" parameter rather than passing commands in via stdin. That is, just call "cmd.exe /k dir". For example,

通常,当尝试使用实际命令调用命令提示符时,使用“/k”参数调用它比通过标准输入传递命令更简单。也就是说,只需调用“cmd.exe /k dir”。例如,

from os import *
a = popen("cmd /k dir")
print (a.read())

The code below does the same thing, though lacks a string for you to manipulate, since it pipes to output directly:

下面的代码做同样的事情,但缺少一个字符串供您操作,因为它直接输出:

from subprocess import *
Popen("cmd /k dir")

回答by ghostdog74

process = subprocess.Popen('cmd.exe /k ', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
process.stdin.write("dir\n")
o,e=process.communicate()
print o
process.stdin.close()

by the way, if your actual task is really to do a directory listing, please use Python's own os module, eg os.listdir(), or glob module... etc. Don't call system commands like that unnecessarily. It makes your code not portable.

顺便说一句,如果你的实际任务真的是做一个目录列表,请使用 Python 自己的 os 模块,例如 os.listdir() 或 glob 模块...等。不要不必要地调用这样的系统命令。它使您的代码不可移植。