如何在python中将不同的命令发送到两个不同的cmd窗口

时间:2018-06-28 08:06:49

标签: python-2.7

我尝试使用子进程模块和win32,但是它没有满足我的要求,因为SendKeys仅在脚本执行过程中不执行任何活动时才起作用

我需要先将adb设备连接到PC,然后通过为每个设备启动命令提示符将“ adb reboot bootloader”命令传递给每个设备

我可以在这方面获得帮助吗?

import time
import re
import win32com.client
'''import win32api
from win32gui import GetWindowText
import win32clipboard
import win32con
from win32gui import GetForegroundWindow
from win32gui import SetForegroundWindow
from win32gui import EnumWindows'''
from win32process import GetWindowThreadProcessId


class ActivateVenv:

    ''' def set_cmd_to_foreground(self, hwnd, extra):
        """sets first command prompt to forgeround"""

        if "cmd.exe" in GetWindowText(hwnd):
            SetForegroundWindow(hwnd)
            return'''

    def get_pid(self):
        """gets process id of command prompt on foreground"""

        #window = GetForegroundWindow()
        #return GetWindowThreadProcessId(window)[0]
        return GetWindowThreadProcessId()

    def activate_venv(self, shell, venv_location):
        """activates venv of the active command prompt"""

        print shell.AppActivate(self.get_pid())

    def run_py_script(self, shell,command):
        """runs the py script"""
        shell.SendKeys(command)

    def open_cmd(self, shell):
        """ opens cmd """

        shell.run("cmd.exe")
        time.sleep(1)


if __name__ == "__main__":
    shell = win32com.client.Dispatch("WScript.Shell")
    run_venv = ActivateVenv()
    command1 = "adb devices>output.txt {ENTER}"
    command3 = "exit {ENTER}"
    #command2 = "fastboot devices {ENTER}"
    #for i in{0,2}:
    run_venv.open_cmd(shell)
    #EnumWindows(run_venv.set_cmd_to_foreground, None)

    run_venv.run_py_script(shell,command1)
    run_venv.run_py_script(shell, command3)
    #run_venv.run_py_script(shell,command2)
    devices_list=[]
    f = open('output.txt', 'r')
    x = f.readlines()
    for i in x:
        r1 = re.findall(r"^\w+",i)
        if r1:
            devices_list.append(r1)
    f.close()
    print devices_list[2]
    #new_device = str(devices_list[2])
    #print(new_device.strip("',[,',]"))

    command2 = "adb -s "+ str(devices_list[2]).strip("',[,',]") + " reboot bootloader {ENTER}"
    run_venv.open_cmd(shell)
    #run_venv.run_py_script(shell, command2)

1 个答案:

答案 0 :(得分:0)

使用subprocess.Popen

from subprocess import Popen, PIPE
p1 = Popen(['cat'], stdin=PIPE, stdout=PIPE)
p2 = Popen(['cat'], stdin=PIPE, stdout=PIPE)
p1.stdin.write(b'hello1\n')
p1.stdin.flush()
print('p1:%s' % p1.stdout.readline())
p2.stdin.write(b'hello2\n')
p2.stdin.flush()
print('p2:%s' % p2.stdout.readline())
p1.stdin.write(b'world1\n')
p1.stdin.flush()
print('p1:%s' % p1.stdout.readline())
p2.stdin.write(b'world2\n')
p2.stdin.flush()
print('p2:%s' % p2.stdout.readline())

这将输出:

p1:hello1
p2:hello2
p1:world1
p2:world2