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

时间:2010-02-23 16:27:26

标签: python windows

我要做的是编写一个只在进程列表中打开应用程序的脚本。意思是它会被“隐藏”。我甚至不知道它是否可能在python中。

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

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

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

有什么想法吗?

4 个答案:

答案 0 :(得分:14)

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

隐藏运行:

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()

运行最小化:

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()

答案 1 :(得分:6)

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

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

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."

答案 2 :(得分:1)

目的是什么?

如果你想在后台运行隐藏(无窗口)进程,最好的方法是编写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)

你可以通过

安装它
python svc_jagteraho.py--startup auto install

并按

运行
python python svc_jagteraho.py start

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

sc stop jagteraho

答案 3 :(得分:0)

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