Background
I have a Python 3.5 console program compiled into a Windows executable via pyinstaller.
Question
How do I detect these different scenarios?
Constraints
Things I've Tried
sys.stdin.isatty()
https://stackoverflow.com/a/3818551/3508142os.isatty(sys.stdout.fileno())
https://stackoverflow.com/a/6108504/3508142
These always return True
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
or explorer.exe
. However, starting the program via the Windows run command will make explorer.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.
You can use psutil. Process().
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!
While installing Python, one IDE named IDLE is also installed. Using the IDLE we can write and also run our programs. But we can also run python programs on CMD or command prompt as CMD is the default command-line interpreter on Windows.
1- Just Right Click the script file and go to properties. 2- Select the option 'Opens with:' in General tab, and select the python from list, if its not available then browse to the installation directory of python and select the python.exe from there. 3- Now when you double click on the file it will run automatically.
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...')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With