简体   繁体   中英

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.

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:

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.

Any ideas?

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

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

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 service can be easily written in python eg here is part of my own service (it will not run without some modifications)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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