2016-12-05 405 views
0

我想要做的是创建一个服务器和一个客户端,服务器能够执行CMD命令。使用python执行CMD命令

我设法做服务器 - 客户端通信,但我在使用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>。我认为它没有显示该线的原因是因为没有输入。

此外,经过一段时间没有输入任何命令它崩溃pexpect.TIMEOUT,我知道我可以通过提高超时解决这个问题,但它并没有改变我的阅读方法有缺陷的事实。

任何人都可以帮我读取命令提示符的输出吗?

对不起,如果我没有描述的问题,我有足够的好,这是我第一次寻求帮助这里计算器:) ...

回答

0

您可以尝试管道输出到输出文件并读取该文件。例如:

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" 
+0

是的,但每次我在os.system中运行一个命令时,它都运行在不同的cmd实例中。我需要将所有命令运行在相同的cmd实例中,以便我可以执行诸如“cd foo”和“dir/d”之类的操作。感谢您的快速回复,虽然 –

+0

@PopescuIonutAlexandru不用担心!我将相应地编辑帖子 –