I use the Windows version of Python. I have a Python script using Pyside (nothing complicated, a kind of "hello world").
When I click on my script file or if I launch it from a command line, it executes perfectly and I have a GUI appearing.
However, I would like to avoid having a GUI if the script is launched from a textual terminal (cmd.exe, cygwin, ...). A kind of script which automatically knows if it should have a GUI output or a textual output.
Is there an easy and simple way to do that? I want to be able to do that with the Windows version of Python (not the one coming with Cygwin packages).
An obvious way would be to add a kind of "--no-gui" parameter when I launch the script from a textual terminal, but I wonder if Python (or some Python libraries) already provide tools for that.
Moreover I have an SSH server (Cygwin-base) on this computer, I can execute the script at distance but no GUI appear (of course) and I have no error message. It is a case where it is very interesting to know if the script failed because of the lack of Windows graphical support or if the script should adapt its output for a textual terminal.
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!
As a standard, it is recommended to use the python3 command or python3. 7 to select a specific version. The py.exe launcher will automatically select the most recent version of Python you've installed. You can also use commands like py -3.7 to select a particular version, or py --list to see which versions can be used.
I know that you can run file as .py file or as .pyw file. The second option is used for GUI applications and it does not open the console window. To distinguish these to two cases you can check isatty
method of sys.stdout
.
import sys
if sys.stdout.isatty():
# .py file is running, with console window
pass
else:
# .pyw file is running, no console
pass
EDIT:
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