【问题标题】:Execute CMD commands using python使用python执行CMD命令
【发布时间】:2016-12-06 23:41:27
【问题描述】:

我要做的是创建一个服务器和一个客户端,服务器能够执行 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,我知道我可以通过提高超时来解决这个问题,但这并不能改变我的阅读方法有缺陷的事实。

谁能帮我阅读命令提示符的输出?

如果我没有描述我遇到的问题,我很抱歉,这是我第一次在 stackoverflow 上寻求帮助 :) ...

【问题讨论】:

    标签: python python-3.x cmd pexpect winpexpect


    【解决方案1】:

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

    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"
    

    【讨论】:

    • 是的,但是每次我在 os.system 中运行命令时,它都会在不同的 cmd 实例中运行。我需要在同一个 cmd 实例中运行所有命令,这样我就可以执行“cd foo”然后是“dir /d”之类的操作。感谢您的快速响应
    • @PopescuIonutAlexandru 不用担心!我会相应地编辑帖子
    • 在尝试运行您的代码时,我总是收到错误:pywintypes.error: (2, 'CreateProcess', 'The system cannot find the file specified.'),指的是 winspawn 行...您知道为什么吗?
    猜你喜欢
    • 2017-11-21
    • 2021-02-19
    • 2012-06-27
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多