Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在windows中打开cmd shell并使用python向该shell发出命令_Python - Fatal编程技术网

如何在windows中打开cmd shell并使用python向该shell发出命令

如何在windows中打开cmd shell并使用python向该shell发出命令,python,Python,我试过了 import os os.system('cmd.exe') 很好,它打开了一个cmd外壳 但是如何从python脚本编写命令,以便打开的shell执行它呢 基本上是这样的 打开一个cmdshell,以某种方式获得打开的shell的实例并向其发出命令。子流程模块似乎没有打开cmd shell,我没有试图通过解释器查看shell的内容,但实际上 但子流程就是这样做的 那么,我们如何打开cmd shell并将命令传递给打开的shell呢 import subprocess process

我试过了

import os
os.system('cmd.exe')
很好,它打开了一个cmd外壳

但是如何从python脚本编写命令,以便打开的shell执行它呢

基本上是这样的

打开一个cmdshell,以某种方式获得打开的shell的实例并向其发出命令。子流程模块似乎没有打开cmd shell,我没有试图通过解释器查看shell的内容,但实际上 但子流程就是这样做的

那么,我们如何打开cmd shell并将命令传递给打开的shell呢

import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
命令变量应该是例如:
cmd/k
。您还可以将
stdin=subprocess.PIPE
添加到Popen参数列表中,并将命令写入cmd:
subprocess.Popen(命令,shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
最终代码:

import subprocess
process = subprocess.Popen('cmd /k ', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
process.stdin.write("dir") #passing command
stdOutput,stdError = process.communicate()
print stdOutput
process.stdin.close()
或者:

from subprocess import *
Popen("cmd /k dir")
命令变量应该是例如:
cmd/k
。您还可以将
stdin=subprocess.PIPE
添加到Popen参数列表中,并将命令写入cmd:
subprocess.Popen(命令,shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
最终代码:

import subprocess
process = subprocess.Popen('cmd /k ', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
process.stdin.write("dir") #passing command
stdOutput,stdError = process.communicate()
print stdOutput
process.stdin.close()
或者:

from subprocess import *
Popen("cmd /k dir")

给任何和我有同样问题的人

我需要在命令提示符窗口上获得一个句柄,并希望激活我的virtualenv并以编程方式运行我的
.py
文件

我使用了pywin32com并在数小时的研究stackoverflow和web之后

我设法找到了一个有效的解决办法

import time
import os
from win32com import client
from  win32gui import GetWindowText, GetForegroundWindow, SetForegroundWindow, 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)[1]

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

        shell.AppActivate(self.get_pid())
        shell.SendKeys("cd \ {ENTER}")
        shell.SendKeys(r"cd %s {ENTER}" % venv_location)
        shell.SendKeys("activate {ENTER}")

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

        shell.SendKeys("cd ../..{ENTER}")
        shell.SendKeys("python run.py {ENTER}")

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

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


if __name__ == "__main__":

    shell = client.Dispatch("WScript.Shell")
    run_venv = ActivateVenv()
    run_venv.open_cmd(shell)
    EnumWindows(run_venv.set_cmd_to_foreground, None)
    run_venv.activate_venv(shell, "flask3.5/venv/scripts")
    run_venv.run_py_script(shell)
我不太了解子流程模块,但我不知道它是否允许您向打开的命令提示符发送不同的命令

但这是我的工作解决方案

import time
import os
from win32com import client
from  win32gui import GetWindowText, GetForegroundWindow, SetForegroundWindow, 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)[1]

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

        shell.AppActivate(self.get_pid())
        shell.SendKeys("cd \ {ENTER}")
        shell.SendKeys(r"cd %s {ENTER}" % venv_location)
        shell.SendKeys("activate {ENTER}")

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

        shell.SendKeys("cd ../..{ENTER}")
        shell.SendKeys("python run.py {ENTER}")

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

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


if __name__ == "__main__":

    shell = client.Dispatch("WScript.Shell")
    run_venv = ActivateVenv()
    run_venv.open_cmd(shell)
    EnumWindows(run_venv.set_cmd_to_foreground, None)
    run_venv.activate_venv(shell, "flask3.5/venv/scripts")
    run_venv.run_py_script(shell)

给任何和我有同样问题的人

我需要在命令提示符窗口上获得一个句柄,并希望激活我的virtualenv并以编程方式运行我的
.py
文件

我使用了pywin32com并在数小时的研究stackoverflow和web之后

我设法找到了一个有效的解决办法

import time
import os
from win32com import client
from  win32gui import GetWindowText, GetForegroundWindow, SetForegroundWindow, 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)[1]

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

        shell.AppActivate(self.get_pid())
        shell.SendKeys("cd \ {ENTER}")
        shell.SendKeys(r"cd %s {ENTER}" % venv_location)
        shell.SendKeys("activate {ENTER}")

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

        shell.SendKeys("cd ../..{ENTER}")
        shell.SendKeys("python run.py {ENTER}")

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

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


if __name__ == "__main__":

    shell = client.Dispatch("WScript.Shell")
    run_venv = ActivateVenv()
    run_venv.open_cmd(shell)
    EnumWindows(run_venv.set_cmd_to_foreground, None)
    run_venv.activate_venv(shell, "flask3.5/venv/scripts")
    run_venv.run_py_script(shell)
我不太了解子流程模块,但我不知道它是否允许您向打开的命令提示符发送不同的命令

但这是我的工作解决方案

import time
import os
from win32com import client
from  win32gui import GetWindowText, GetForegroundWindow, SetForegroundWindow, 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)[1]

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

        shell.AppActivate(self.get_pid())
        shell.SendKeys("cd \ {ENTER}")
        shell.SendKeys(r"cd %s {ENTER}" % venv_location)
        shell.SendKeys("activate {ENTER}")

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

        shell.SendKeys("cd ../..{ENTER}")
        shell.SendKeys("python run.py {ENTER}")

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

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


if __name__ == "__main__":

    shell = client.Dispatch("WScript.Shell")
    run_venv = ActivateVenv()
    run_venv.open_cmd(shell)
    EnumWindows(run_venv.set_cmd_to_foreground, None)
    run_venv.activate_venv(shell, "flask3.5/venv/scripts")
    run_venv.run_py_script(shell)

看看python子进程库。谷歌搜索。你需要保持它打开吗?这是一辆出租车吗?你真正需要实现什么?@PeterWood是的,我需要打开外壳,只是用一个script@pregmatch我需要实际的cmd shell,而不仅仅是一个子进程,以便向解释器查看命令。子流程可以这样做吗?打开cmd shell并将参数传递给打开的shell?看看python子进程库。谷歌搜索。你需要保持它打开吗?这是一辆出租车吗?你真正需要实现什么?@PeterWood是的,我需要打开外壳,只是用一个script@pregmatch我需要实际的cmd shell,而不仅仅是一个子进程,以便向解释器查看命令。子流程可以这样做吗?打开cmd shell并将参数传递给打开的shell?第3行有错误
process.stdin.write(“dir”)TypeError:需要一个类似字节的对象,而不是“str”
第3行有一个错误
process.stdin.write(“dir”)TypeError:需要一个类似字节的对象,而不是“str”
很好的解决方案!伟大的解决方案!