背景
我有一个通过pyinstaller编译成Windows可执行文件的Python 3.5控制台程序。
问题
如何检测这些不同的情况?
约束
我尝试过的事情
sys.stdin.isatty()
https://stackoverflow.com/a/3818551/3508142
os.isatty(sys.stdout.fileno())
https://stackoverflow.com/a/6108504/3508142
在Windows上,它们总是返回True
。
搜索StackOverflow /互联网:
How to determine if Python script was run via command line?
How can I check to see if a Python script was started interactively?
据我了解,无论用户是从命令提示符还是GUI启动程序,该程序都会以交互方式运行 。
我还考虑检查父进程是cmd.exe
还是explorer.exe
。但是,通过Windows运行命令启动程序将使explorer.exe
成为父进程。通过任务管理器启动程序将使任务管理器成为父进程。这些是我可以可以忍受的极端情况,但显然我更希望使用更可靠的解决方案。
答案 0 :(得分:1)
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...')
答案 1 :(得分:0)
结果证明,有一种简单明了的方法可以在Windows上确定此问题。 https://stackoverflow.com/a/14394730/3508142
PROMPT
环境变量在命令提示符下定义提示符文本。
https://ss64.com/nt/prompt.html
# If the program was started via the GUI (i.e. by double-clicking the executable),
# then prevent the console window from closing automatically.
if os.name == 'nt' and 'PROMPT' not in os.environ:
input('Press ENTER to continue...')