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

标签 python python-3.x windows pyinstaller

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

问题

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

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

约束

  1. 可执行文件必须能够在基本(即全新安装)Windows/RedHat 机器上运行。
  2. 编译 可执行文件必须是单个文件,并且不能依赖未打包在已编译可执行文件中的其他文件(pyinstaller 允许将文件打包在已编译可执行文件中)。
  3. 该程序可能依赖于第 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...')

关于python - 检测 python 程序是否通过 Windows GUI(双击)与命令提示符执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55172090/

相关文章:

c++ - 使用 IDispatch::Invoke 的 OLE 交互参数构造

windows - 适用于 Windows 的补丁堆栈工具

python - 无法在Windows上通过pip安装netCDF4

python - 坐标列表中的半径搜索

python - 尝试使用 Anaconda-navigator 安装 Tensorflow 但在导航器中找不到该包

python-3.x - ImportError : libcublas. so.9.0:无法打开共享对象文件

python - 将单词 Null 添加到 CSV 文件

python - 从 Shapefile 获取邻接矩阵

Python查找两个不同长度的数据框列的部分匹配

python-3.x - XLSXWriter 使用动态单元格引用跨列应用公式