Eri*_*mus 5 python windows pyinstaller python-3.x
背景
我有一个 Python 3.5 控制台程序通过 pyinstaller 编译成 Windows 可执行文件。
题
我如何检测这些不同的场景?
约束
我尝试过的事情
sys.stdin.isatty()
/sf/answers/267298601/
os.isatty(sys.stdout.fileno())
/sf/answers/427595311/
这些总是True在 Windows 上返回。
搜索 StackOverflow/互联网:
如何确定 Python 脚本是否通过命令行运行?
如何检查 Python 脚本是否以交互方式启动?
据我所知,如果用户启动了程序,无论它是从命令提示符还是 GUI 启动,它都会以交互方式运行。
我还考虑检查父进程是否为cmd.exe或explorer.exe。但是,通过 Windows 运行命令启动程序将使explorer.exe父进程。通过任务管理器启动程序将使任务管理器成为父进程。这些是我可以忍受的边缘情况,但显然我更喜欢更强大的解决方案。
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 次 |
| 最近记录: |