Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we know if a Python script is launched from Windows or a textual terminal?

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.

like image 996
Vincent Hiribarren Avatar asked Apr 12 '12 07:04

Vincent Hiribarren


People also ask

How can I tell if Python script is running on Windows?

You can use psutil. Process().

How do I run a Python script in Windows?

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!

How to run a certain version of Python?

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.


1 Answers

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:

  • I tried to run that with putty+ssh on linux box - it returns True.
  • I tried to use msys bash shell on windows box - it returns True (.py file)
  • I tried to use cygwin bash shell with cygwin python - it returns True (.py file)
  • Unfortunately, I have no possibility to try putty + windows cygwin ssh server.
like image 101
Jiri Avatar answered Sep 27 '22 21:09

Jiri