检测python程序是否通过Windows GUI(双击)vs命令提示符执行

Eri*_*mus 5 python windows pyinstaller python-3.x

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

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

我如何检测这些不同的场景?

约束

  1. 可执行文件必须能够在准系统(即全新安装)Windows/RedHat 机器上运行。
  2. 编译可执行文件必须是单个文件,可以不依赖于编译的可执行文件中没有打包的其他文件(pyinstaller允许文件内编译的可执行文件打包)。
  3. 该程序可能依赖于 3rd 方 python 包。

我尝试过的事情

Eri*_*mus 6

计算附加到控制台的进程数

GetConsoleProcessList 的 Windows API 文档

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...')
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

980 次

最近记录:

6 年,11 月 前