windows 用最小化或隐藏的python打开一个程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2319838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:00:44  来源:igfitidea点击:

Open a program with python minimized or hidden

pythonwindows

提问by wtz

What I'm trying to do is to write a script which would open an application only in process list. Meaning it would be "hidden". I don't even know if its possible in python.

我想要做的是编写一个脚本,它只能在进程列表中打开一个应用程序。这意味着它将被“隐藏”。我什至不知道在 python 中是否可能。

If its not possible, I would settle for even a function that would allow for a program to be opened with python in a minimized state maybe something like this:

如果不可能,我什至会接受一个允许程序在最小化状态下用python打开的函数,可能是这样的:

import subprocess
def startProgram():
    subprocess.Hide(subprocess.Popen('C:\test.exe')) #  I know this is wrong but you get the idea...
startProgram()

Someone suggested to use win32com.client but the thing is that the program that i want to launch doesn't have a COM server registered under the name.

有人建议使用 win32com.client,但问题是我要启动的程序没有以该名称注册的 COM 服务器。

Any ideas?

有任何想法吗?

回答by Tomer Zait

It's easy :)
Python Popen Accept STARTUPINFO Structure...
About STARTUPINFO Structure: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx

这很容易:)
Python Popen 接受 STARTUPINFO 结构...
关于 STARTUPINFO 结构:https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331( v=vs.85).aspx

Run Hidden:

运行隐藏:

import subprocess

def startProgram():
    SW_HIDE = 0
    info = subprocess.STARTUPINFO()
    info.dwFlags = subprocess.STARTF_USESHOWWINDOW
    info.wShowWindow = SW_HIDE
    subprocess.Popen(r'C:\test.exe', startupinfo=info)
startProgram()

Run Minimized:

运行最小化:

import subprocess

def startProgram():
    SW_MINIMIZE = 6
    info = subprocess.STARTUPINFO()
    info.dwFlags = subprocess.STARTF_USESHOWWINDOW
    info.wShowWindow = SW_MINIMIZE
    subprocess.Popen(r'C:\test.exe', startupinfo=info)
startProgram()

回答by Anurag Uniyal

You should use win32api and hide your window e.g. using win32gui.EnumWindowsyou can enumerate all top windows and hide your window

您应该使用 win32api 并隐藏您的窗口,例如使用win32gui.EnumWindows您可以枚举所有顶级窗口并隐藏您的窗口

Here is a small example, you may do something like this:

这是一个小例子,你可以这样做:

import subprocess
import win32gui
import time

proc = subprocess.Popen(["notepad.exe"])
# lets wait a bit to app to start
time.sleep(3)

def enumWindowFunc(hwnd, windowList):
    """ win32gui.EnumWindows() callback """
    text = win32gui.GetWindowText(hwnd)
    className = win32gui.GetClassName(hwnd)
    #print hwnd, text, className
    if text.find("Notepad") >= 0:
        windowList.append((hwnd, text, className))

myWindows = []
# enumerate thru all top windows and get windows which are ours
win32gui.EnumWindows(enumWindowFunc, myWindows)

# now hide my windows, we can actually check process info from GetWindowThreadProcessId
# http://msdn.microsoft.com/en-us/library/ms633522(VS.85).aspx
for hwnd, text, className in myWindows:
    win32gui.ShowWindow(hwnd, False)

# as our notepad is now hidden
# you will have to kill notepad in taskmanager to get past next line
proc.wait()
print "finished."

回答by Anurag Uniyal

What is the purpose?

什么目的?

if you want a hidden(no window) process working in background, best way would be to write a windows service and start/stop it using usual window service mechanism. Windows service can be easily written in python e.g. here is part of my own service (it will not run without some modifications)

如果你想要一个隐藏的(无窗口)进程在后台工作,最好的方法是编写一个 Windows 服务并使用通常的窗口服务机制启动/停止它。Windows 服务可以很容易地用 python 编写,例如这里是我自己服务的一部分(如果不做一些修改,它将无法运行)

import os
import time
import traceback

import pythoncom
import win32serviceutil
import win32service
import win32event
import servicemanager

import jagteraho


class JagteRahoService (win32serviceutil.ServiceFramework):
    _svc_name_ = "JagteRaho"
    _svc_display_name_ = "JagteRaho (KeepAlive) Service"
    _svc_description_ = "Used for keeping important services e.g. broadband connection up"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.stop = False

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.log('stopping')
        self.stop = True

    def log(self, msg):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_,msg))

    def SvcDoRun(self):
        self.log('folder %s'%os.getcwd())
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        self.start()

    def shouldStop(self):
        return self.stop

    def start(self):
        try:
            configFile = os.path.join(jagteraho.getAppFolder(), "jagteraho.cfg")
            jagteraho.start_config(configFile, self.shouldStop)
        except Exception,e:
            self.log(" stopped due to eror %s [%s]" % (e, traceback.format_exc()))
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)


if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)

and you can install it by

你可以安装它

python svc_jagteraho.py--startup auto install

and run it by

并运行它

python python svc_jagteraho.py start

I will be also be seen in services list e.g. services.msc will show it and you can start/stop it else you can use commandline

我也会出现在服务列表中,例如 services.msc 会显示它,你可以启动/停止它,否则你可以使用命令行

sc stop jagteraho

回答by Mike Graham

If what is appearing is a terminal, redirect the process's stdout.

如果出现的是终端,则重定向进程的标准输出。