问题描述
我想做的是创建一个服务器和一个客户端,该服务器能够执行CMD命令.
what i'm trying to do is create a server and a client, the server being able to execute CMD commands.
我设法进行服务器-客户端通信,但是在使用python控制命令提示符时遇到问题.
I managed to do the server-client communication but i have problems at controlling the command prompt using python.
我当前的代码是:
import time
import _thread
import winpexpect
class CommandPrompt(object):
def __init__(self):
self.cmd = winpexpect.winspawn('cmd.exe')
def read(self):
while True:
if self.cmd.readline():
print(self.cmd.before)
def send(self,usinput):
self.cmd.sendline(usinput)
def close(self):
self.cmd.close()
cmd = CommandPrompt()
_thread.start_new_thread(cmd.read,())
time.sleep(1)
while True:
cmd.send(input('>>'))
使用此代码,我能够执行shell命令,但总是缺少最后一行,该行显示了当前路径并等待我的输入 ex:C:\ Windows \ system32>
.我认为未显示该行的原因是因为未输入该行.
With this code i am able to execute shell commands but it always i missing the last line, the one showing the current path and waiting for my input ex:C:\Windows\system32>
. I think the reason it's not showing that line is because it wasn't entered.
此外,一段时间未输入任何命令后,它崩溃了 pexpect.TIMEOUT
,我知道我可以通过增加超时来解决此问题,但它不会改变我的阅读方法存在缺陷的事实
Also, after some time of not inputting any command it crashes pexpect.TIMEOUT
, i know i could solve this by raising the timeout but it doesn't change the fact that my reading method is flawed.
有人可以帮助我阅读命令提示符的输出吗?
Can anyone help me to read the output of the command prompt?
很抱歉,如果我没有描述问题,我已经足够好了,这是我第一次在这里寻求有关stackoverflow的帮助:)...
I'm sorry if i didn't describe the problem i have good enough, it's my first time asking for help here on stackoverflow :)...
推荐答案
您可以尝试将输出传递到输出文件中并读取该文件.例如:
You could try to pipe the output into an output file and read that file. For example:
import time
import _thread
import winpexpect
class CommandPrompt(object):
def __init__(self):
self.cmd = winpexpect.winspawn('cmd.exe')
def read(self):
while True:
if self.cmd.readline():
print(self.cmd.before)
def send(self,usinput):
self.cmd.sendline(usinput)
def close(self):
self.cmd.close()
cmd = CommandPrompt()
_thread.start_new_thread(cmd.read,())
time.sleep(1)
while True:
cmd.send(input('>>') + " > out.txt")
# some sort of function to request the contents of "out.txt"
# some sort of function to remove "out.txt"
这篇关于使用python执行CMD命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!