Background
I have a Python 3.5 console program compiled into a Windows executable via pyinstaller.
Question
- When executed via a command prompt, I'd like my program to run with whatever arguments were supplied (possibly none).
- When executed via the operating system's GUI (i.e. by double-clicking the .exe in Windows Explorer on Windows, etc) I'd like my program to prompt the user for input. I also need my program to pause before exiting so the user can read the output.
How do I detect these different scenarios?
Constraints
- The executable must be able to run on a bare-bones (i.e. fresh install) Windows/RedHat machine.
- The compiled executable must be a single file and may not rely on other files not packaged inside the compiled executable (pyinstaller allows files to be packaged inside the compiled executable).
- The program may depend on 3rd party python packages.
Things I've Tried
sys.stdin.isatty()
https://stackoverflow.com/a/3818551/3508142
os.isatty(sys.stdout.fileno())
https://stackoverflow.com/a/6108504/3508142
These always returnTrue
on Windows.Searching StackOverflow / the internet:
How to determine if Python script was run via command line?
How can I check to see if a Python script was started interactively?
As far as I understand, a program is running interactively if the user started it regardless of whether it was started from a command prompt or the GUI.I also considered checking to see if the parent process is
cmd.exe
orexplorer.exe
. However, starting the program via the Windows run command will makeexplorer.exe
the parent process. Starting the program via Task Manager will make Task Manager the parent process. These are edge cases that I could live with, but obviously I'd prefer a more robust solution.