我试图让我的基本python脚本打开并写入和读取cmd,以便允许它向noxplayer发送命令。我正在尝试使用子流程,并且发现并了解了使用PIPES而不是使用它们。无论哪种方式,我都可以使用它来发送输入,从而导致一系列不同的断点。这是我尝试过的2个代码示例。
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
我做错了什么,正确的做法是什么?
communicate
很棒,因为它能够分别读取标准输出和错误。
但是否则它很笨拙,因为它只发送一次输入。因此,一旦发生这种情况:
stdout, stderr = self.cmd.communicate()
完成后,您将无法向流程发送更多输入。
另一种方法是:
但在这里这会太过分了。什么是矫枉过正首先是Popen
在Windowscmd
的过程,当你不需要它在所有。加上cd
命令,再加上输入提要,再加上shell=True
...
简单一点
而是Popen
直接在nox
循环中的命令上使用(可能在两次调用之间有很小的延迟)。
我没有进行测试,但这是一种在给定目录中重复运行带有参数的命令并读取其输出的独立方法。
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)
ifnox_adb
是一个.bat
不会被剪切的文件,在这种情况下,命令的前缀为cmd /c
:
p = subprocess.Popen(["cmd","/c","nox_adb","devices"],cwd="C:/Program Files (x86)/Nox/bin",stdout=subprocess.PIPE)
这大致相当于shell=True
在Windows上添加,但是这shell=True
是一种解决问题的懒惰方法,就像回飞镖一样,几年后又出现在您的脑海中,因此最好在工业解决方案中避免它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句