【问题标题】:how to open a cmd shell in windows and issue commands to that shell using python如何在 Windows 中打开 cmd shell 并使用 python 向该 shell 发出命令
【发布时间】:2016-01-08 16:18:43
【问题描述】:

我试过了

import os
os.system('cmd.exe')

很好,它打开了一个 cmd shell

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

基本上是这样的

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

那么我们如何打开一个 cmd shell 并将命令传递给打开的 shell?

【问题讨论】:

  • 看看python子进程库。谷歌一下。
  • 您需要保持打开状态吗?这是XY problem 吗?你真正需要实现什么?
  • @PeterWood 是的,我需要打开外壳,它只是为了使用脚本激活我的 virtualenv
  • @pregmatch 我需要实际的 cmd shell 而不仅仅是一个子进程来查看解释器。子进程可以做到吗?打开一个 cmd shell 并将参数传递给打开的 shell ?

标签: python


【解决方案1】:

给和我有同样问题的人

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

我使用 pywin32com 并经过数小时研究 stackoverflow 和网络

我设法找到了一个可行的解决方案

我对子进程模块了解不多,但我不知道它是否能让你向打开的命令提示符

发送不同的命令

但这是我的工作解决方案

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)

【讨论】:

  • 很好的解决方案!
【解决方案2】:
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(command, 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")

【讨论】:

  • 第3行有错误。process.stdin.write("dir") TypeError: a bytes-like object is required, not 'str'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 2014-01-20
相关资源
最近更新 更多