简体   繁体   English

用子进程包装cmd.exe

[英]wrapping cmd.exe with subprocess

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. 我尝试使用以下程序在Windows下包装cmd.exe但它不起作用,它似乎等待某些东西并且不显示任何内容。 Any idea what is wrong here ? 知道这里有什么问题吗?

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

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. 通常在尝试使用实际命令调用命令提示符时,使用“/ k”参数调用它更简单,而不是通过via stdin传递命令。 That is, just call "cmd.exe /k dir". 也就是说,只需调用“cmd.exe / k dir”即可。 For example, 例如,

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")
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. 顺便说一下,如果你的实际任务是真的要做一个目录列表,请使用Python自己的os模块,例如os.listdir()或glob模块......等等。不要不必要地调用那样的系统命令。 It makes your code not portable. 它使您的代码不可移植。

This locks up because process.stdout.readlines() reads all output by the process (until it terminates). 这会锁定,因为process.stdout.readlines()读取进程的所有输出(直到它终止)。 Since cmd.exe is still running, it keeps waiting forever for it to close. 由于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. 如果你不调用communicate() ,这是你需要做的事情,以避免可能的死锁。 This thread can call process.stdout.readline() repeatedly and handle the data or send it back to the main thread for handling. 该线程可以重复调用process.stdout.readline()并处理数据或将其发送回主线程进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM