Can we find out if a Python script is running from Windows or a text terminal?

I am using the Python version for Windows. I have a Python script using Pyside (nothing complicated, a kind of "hello world").

When I click on my script file or run it from the command line, it works fine and I get a GUI.

However, I would like to avoid using the GUI if the script is run from a text terminal (cmd.exe, cygwin, ...). A kind of script that automatically knows if it should have a graphical interface or text output.

Is there a simple and easy way to do this? I want to be able to do this using a version of Windows Python (and not the one that comes with Cygwin packages).

The obvious way would be to add some kind of "--no-gui" option when running the script from the text terminal, but I am wondering if Python (or some Python libraries) can provide tools for this.

In addition, I have an SSH server (Cygwin-base) on this computer, I can execute the script from a distance, but the GUI (of course) is not displayed (and, of course, I do not have an error message). This is the case when it is very interesting to know if the script failed due to the lack of graphical support for Windows or if the script should adapt its output for the text terminal.

+7
source share
1 answer

I know that you can run the file as a .py file or a .pyw file. The second option is used for graphical applications, and it does not open a console window. To distinguish them from two cases, you can check the isatty sys.stdout method.

 import sys if sys.stdout.isatty(): # .py file is running, with console window pass else: # .pyw file is running, no console pass 

EDIT

  • I tried to run this using putty + ssh in the linux box - it returns True.
  • I tried using msys bash shell in window window - it returns True (.py file)
  • I tried using the cygwin bash shell with cygwin python - it returns True (.py file)
  • Unfortunately, I have no way to try putty + windows cygwin ssh server.
+1
source

All Articles