简体   繁体   English

在后台启动Python程序

[英]Start Python program in the background

I have a Python program which I compiled into a .exe file using PyInstaller. 我有一个使用PyInstaller编译成.exe文件的Python程序。 When you open the .exe, there should be no console, no command prompt or whatever. 当您打开.exe时,应该没有控制台,没有命令提示符或任何其他内容。 It should run the Python program in the background completely silently. 它应该完全在后台静默运行Python程序。

Is it possible to put something in the Python script so that it does not open a command prompt and executes silently? 是否可以在Python脚本中放入某些内容,使其不打开命令提示符并以静默方式执行?

Yes, on windows you can create a bat-file like this: 是的,在Windows上您可以创建一个bat文件,如下所示:

start /B your_file.exe

add this code to your app: 将此代码添加到您的应用中:

import ctypes
import os
import win32process

hwnd = ctypes.windll.kernel32.GetConsoleWindow()      

    if hwnd != 0:      
        ctypes.windll.user32.ShowWindow(hwnd, 0)      
        ctypes.windll.kernel32.CloseHandle(hwnd)
        _, pid = win32process.GetWindowThreadProcessId(hwnd)
        os.system('taskkill /PID ' + str(pid) + ' /f')

Save this one line of text as file invisible.vbs: 将这一行文本保存为文件invisible.vbs:

CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False

To run any program or batch file invisibly, use it like this: 要隐式运行任何程序或批处理文件,请按以下方式使用它:

wscript.exe "C:\Wherever\invisible.vbs" "C:\Some Other Place\MyBatchFile.bat"

To also be able to pass-on/relay a list of arguments use only two double quotes 为了也可以传递/中继参数列表,请仅使用两个双引号

CreateObject("Wscript.Shell").Run "" & WScript.Arguments(0) & "", 0, False

Example: Invisible.vbs "Kill.vbs ME.exe" 示例:Invisible.vbs“ Kill.vbs ME.exe”

您可以使用--noconsole选项,如果不起作用,请将spec文件设置“ console”更改为False。

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

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