简体   繁体   English

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

[英]Open a program with python minimized or hidden

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?有任何想法吗?

It's easy :)这很简单 :)
Python Popen Accept STARTUPINFO Structure... Python Popen 接受 STARTUPINFO 结构...
About STARTUPINFO Structure: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx关于 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()

You should use win32api and hide your window eg using win32gui.EnumWindows you 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."

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 服务并使用通常的窗口服务机制启动/停止它。 Windows service can be easily written in python eg here is part of my own service (it will not run without some modifications) 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 eg services.msc will show it and you can start/stop it else you can use commandline我也会出现在服务列表中,例如 services.msc 会显示它,你可以启动/停止它,否则你可以使用命令行

sc stop jagteraho

Run Hidden:运行隐藏:

from subprocess_maximize import Popen
Popen("notepad.exe",show='hidden', priority=0)

Before the code above, use the following command:在上面的代码之前,使用以下命令:

pip install subprocess-maximize

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM