2010-02-23 12 views
5

Quello che sto cercando di fare è scrivere uno script che aprirebbe un'applicazione solo nella lista dei processi. Significa che sarebbe "nascosto". Non so nemmeno se è possibile in Python.Aprire un programma con python minimizzato o nascosto

Se proprio non è possibile, mi accontenterei anche per una funzione che consenta un programma da aprire con Python in uno stato minimizzato forse qualcosa di simile:

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

Qualcuno ha suggerito di utilizzare win32com.client ma il fatto è che il programma che voglio lanciare non ha un server COM registrato sotto il nome.

Qualche idea?

risposta

6

Si dovrebbe usare Win32API e nascondere la finestra per esempio utilizzando win32gui.EnumWindows è possibile enumerare tutte le finestre superiori e nascondere la finestra

Ecco un piccolo esempio, si può fare qualcosa di simile:

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

Ti capita di conoscere il modulo corrispondente su Linux? – helplessKirk

0

Se ciò che appare è un terminale, reindirizzare lo stdout del processo.

+0

Non è un terminale. – wtz

1

Qual è lo scopo?

se si desidera che un processo nascosto (senza finestra) funzioni in background, il modo migliore sarebbe scrivere un servizio Windows e avviarlo/arrestarlo utilizzando il solito meccanismo di servizio delle finestre. Il servizio Windows può essere facilmente scritto in python, ad es. qui è parte del mio proprio servizio (che non verrà eseguito senza alcune modifiche)

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) 

ed è possibile installarlo da

python svc_jagteraho.py--startup auto install 

ed eseguirlo da

python python svc_jagteraho.py start 

sarò anche essere visto nella lista dei servizi ad es services.msc mostrerà esso e si può avviare/fermare altro si può usare da riga di comando

sc stop jagteraho 
+1

Penso che questo sia esagerato in termini di ciò che voglio. Lo scopo dello script è eseguire un programma nascosto (senza finestra) solo quando si avvia lo script. Il programma che voglio nascondere è un'applicazione proprietaria che fa un certo numero di crunch e viene scritta penso in C. Python fondamentalmente lo nasconde e recupera i progressi in una finestra di GUI trasparente e minimalista molto bella che ho scritto. Niente di importante. Il problema è che non voglio che questa enorme finestra fluttui intorno al mio desktop, quindi voglio nasconderlo. – wtz

+0

@wtzolt, dipende, ma per lungo tempo il servizio di background process è il modo migliore, comunque ho aggiunto un'altra soluzione per nascondere qualsiasi tipo di finestra, quindi dovrebbe funzionare anche con la tua app –

+0

@wtz forse questo è un po 'fuori moda ma lì è un piccolo ed elegante strumento chiamato "Power Menu" http://www.abstractpath.com/powermenu/ che porta alcune funzionalità di un importante desktop * ix in windows, ad es. Minimizza al vassoio o sempre in primo piano – enthus1ast

10

E 'facile :)
Python Popen Accetta STARTUPINFO Struttura ...
Circa STARTUPINFO Struttura: 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() 

Avvia ridotto a icona:

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