11

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?

Mike Graham
  • 73,987
  • 14
  • 101
  • 130
wtz
  • 375
  • 1
  • 5
  • 18

5 Answers5

35

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()
Tomer Zait
  • 1,756
  • 2
  • 14
  • 12
8

You should use win32api and hide your window e.g. 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."
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
0

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)

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

sc stop jagteraho
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
  • 1
    I think this is over the top in terms of what i want. The purpose of the script is to run a program hidden(no window) only when you start the script. The program that i want to hide is a proprietary application that does some number crunching and is written i think in C. Python basically hides it and fetches the progress in a very nice minimalistic transparent GUI window that i written. Nothing major. The problem is that i don't want this huge window to be floating around my desktop so i want to hide it. – wtz Feb 23 '10 at 17:02
  • @wtzolt , it depends, but for long running background process service is the best way, anyway i added another solution to hide any type of window, so it should work with your app too – Anurag Uniyal Feb 24 '10 at 03:00
  • @wtz maybe this is a little offtopic but there is a neat little tool out there called "Power Menu" http://www.abstractpath.com/powermenu/ it brings some features of a major *ix desktop to windows eg. Minimize to tray or always on top – enthus1ast Jan 31 '14 at 15:37
0

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
  • please add a little more info about how or why this works to improve you answer and give a little more context, thanks! – n4321d Jul 20 '22 at 16:58
-2

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

Mike Graham
  • 73,987
  • 14
  • 101
  • 130