簡體   English   中英

如何在Windows中打開cmd外殼並使用python向該外殼發出命令

[英]how to open a cmd shell in windows and issue commands to that shell using python

我試過了

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

很棒,它打開了一個cmd外殼

但是如何從python腳本編寫命令,以便打開的shell執行它?

基本上就是這樣

打開一個cmd shell,然后以某種方式獲取已打開shell的實例並對其執行命令。 子進程模塊似乎沒有打開cmd shell,即不是試圖通過解釋器查看shell的內容,但實際上那是子進程的作用?

那么我們如何打開cmd shell並將命令傳遞給該打開的shell?

給與我有同樣問題的人

我需要在命令提示符窗口上找到一個句柄,並想要激活我的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)
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode

命令變量應該是例如: cmd /k 您還可以在Popen參數列表中添加stdin=subprocess.PIPE subprocess.PIPE並將命令寫入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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM