使用cmd处理python

2024-06-12 17:13:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试打开我的基本python脚本,并对cmd进行写入和读取,以便允许它向noxplayer发送命令。我正在尝试使用子进程,并且已经发现并阅读了关于使用管道和不使用管道的内容。无论哪种方式,我都可以让它发送输入,从而产生一系列不同的断点。下面是我尝试过的两个代码示例

class bot:
    def __init__(self, num):
        self.num = num

    def start(self):
        #open app and command prompt
        androidArg1 = "C:/Program Files (x86)/Nox/bin/Nox.exe"
        androidArg2 = "-clone:Nox_" + str(self.num)
        androidArgs = [androidArg1, androidArg2]
        cmdArg1 = 'cmd'
        cmdArgs = [cmdArg1]
        self.app = subprocess.Popen(androidArgs)
        self.cmd = subprocess.Popen(cmdArgs, shell=True)

        self.cmd.communicate(input="cd C:/Program Files (x86)/Nox/bin")
        while True:
            self.devices = self.cmd.communicate(input="nox_adb devices")
            print(self.devices)

正在打印C:\Users\thePath>,但从未完成第一次通信

class bot:
    def __init__(self, num):
        self.num = num

    def start(self):
        #open app and command prompt
        androidArg1 = "C:/Program Files (x86)/Nox/bin/Nox.exe"
        androidArg2 = "-clone:Nox_" + str(self.num)
        androidArgs = [androidArg1, androidArg2]
        cmdArg1 = 'cmd'
        cmdArgs = [cmdArg1]
        self.app = subprocess.Popen(androidArgs)
        self.cmd = subprocess.Popen(cmdArgs, stdin=PIPE, stderr=PIPE, stdout=PIPE, universal_newlines=True, shell=True)
        stdout, stderr = self.cmd.communicate()
        stdout, stderr


        self.cmd.communicate(input="cd C:/Program Files (x86)/Nox/bin")
        while True:
            self.devices = self.cmd.communicate(input="nox_adb devices")
            print(self.devices)

投掷

Cannot send input after starting communication

我做错了什么?正确的做法是什么


Tags: selfcmdtrueappinputbindeffiles
1条回答
网友
1楼 · 发布于 2024-06-12 17:13:05

communicate非常好,因为它能够分别读取标准输出和错误

但除此之外,它相当笨重,因为它只发送一次输入。因此,一旦发生这种情况:

stdout, stderr = self.cmd.communicate()

结束了,您无法向流程发送更多输入

另一种方法是:

  • 将输入逐行输入到流程
  • 合并标准输出和错误(以避免死锁)

但在这里,这将是矫枉过正。首先,在Windows cmd进程上执行Popen是一种过分的做法,而您根本不需要它。加上cd命令,加上输入提要,再加上shell=True

简单化

相反,直接在循环中的nox命令上使用Popen(调用之间可能会有一点延迟)

我没有对此进行测试,但这是一种自包含的方法,可以在给定目录中反复运行带有参数的命令,并读取其输出

import time,subprocess
while True:
    p = subprocess.Popen(["nox_adb","devices"],cwd="C:/Program Files (x86)/Nox/bin",stdout=subprocess.PIPE)
    devices = p.stdout.read().decode()
    rc = p.wait()   # wait for process to end & get return code
    if rc:
       break  # optional: exit if nox_adb command fails
    time.sleep(1)

如果nox_adb是一个不会剪切它的.bat文件,在这种情况下,以cmd /c作为命令的前缀:

    p = subprocess.Popen(["cmd","/c","nox_adb","devices"],cwd="C:/Program Files (x86)/Nox/bin",stdout=subprocess.PIPE)

这大致相当于在Windows上添加shell=True,但shell=True是一种懒散的解决问题的方法,多年后它会像回飞棒一样回到你的脑海中,所以最好在工业解决方案中避免它

相关问题 更多 >