检测是否通过Windows GUI(双击)与命令提示符执行Python程序 [英] Detect if python program is executed via Windows GUI (double-click) vs command prompt

查看:23
本文介绍了检测是否通过Windows GUI(双击)与命令提示符执行Python程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景
我有一个Python 3.5控制台程序通过pyinstaller编译成Windows可执行文件。

问题

  • 通过命令提示符执行时,我希望我的程序使用提供的任何参数(可能没有)运行。
  • 通过操作系统的GUI执行时(即在Windows上双击Windows资源管理器中的.exe等),我希望我的程序提示用户输入。我还需要程序在退出前暂停,以便用户可以阅读输出。

如何检测这些不同的方案?

约束

  1. 该可执行文件必须能够在基本(即全新安装)Windows/RedHat计算机上运行。
  2. 编译的可执行文件必须是单个文件,并且不能依赖未打包在编译的可执行文件中的其他文件(pyinstaller允许将文件打包在编译的可执行文件中)。
  3. 该程序可能依赖于第三方python包。

我尝试过的内容

推荐答案

统计附加到控制台的进程

Windows API documentation for GetConsoleProcessList

import ctypes

# Load kernel32.dll
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
# Create an array to store the processes in.  This doesn't actually need to
# be large enough to store the whole process list since GetConsoleProcessList()
# just returns the number of processes if the array is too small.
process_array = (ctypes.c_uint * 1)()
num_processes = kernel32.GetConsoleProcessList(process_array, 1)
# num_processes may be 1 if your compiled program doesn't have a launcher/wrapper.
if num_processes == 2:
    input('Press ENTER to continue...')

这篇关于检测是否通过Windows GUI(双击)与命令提示符执行Python程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆