pythonw.exe or python.exe? - python

Long story short: pythonw.exe does nothing, python.exe accepts nothing (which one should I use?)
test.py:
print "a"
CMD window:
C:\path>pythonw.exe test.py
<BLANK LINE>
C:\path>
C:\path>python.exe test.py
File "C:\path\test.py", line 7
print "a"
^
SyntaxError: invalid syntax
C:\path>
Please tell me what I'm doing terrible wrong.

To summarize and complement the existing answers:
python.exe is a console (terminal) application for launching CLI-type scripts (console applications).
Unless run from an existing console window, python.exe opens a new console window.
Standard streams sys.stdin, sys.stdout and sys.stderr are connected to the console window.
Execution is synchronous when launched from a cmd.exe or PowerShell console window: See eryksun's 1st comment below.
If a new console window was created, it stays open until the script terminates.
When invoked from an existing console window, the prompt is blocked until the script terminates.
pythonw.exe is a GUI app for launching GUI/no-UI-at-all scripts.
NO console window is opened.
Execution is asynchronous:
When invoked from a console window, the script is merely launched and the prompt returns right away, whether the script is still running or not.
Standard streams sys.stdin, sys.stdout and sys.stderr are NOT available.
Caution: Unless you take extra steps, this has potentially unexpected side effects:
Unhandled exceptions cause the script to abort silently.
In Python 2.x, simply trying to use print() can cause that to happen (in 3.x, print() simply has no effect).
To prevent that from within your script, and to learn more, see this answer of mine.
Ad-hoc, you can use output redirection:Thanks, #handle.
pythonw.exe yourScript.pyw 1>stdout.txt 2>stderr.txt
(from PowerShell:
cmd /c pythonw.exe yourScript.pyw 1>stdout.txt 2>stderr.txt) to capture stdout and stderr output in files.
If you're confident that use of print() is the only reason your script fails silently with pythonw.exe, and you're not interested in stdout output, use #handle's command from the comments:
pythonw.exe yourScript.pyw 1>NUL 2>&1
Caveat: This output redirection technique does not work when invoking *.pyw scripts directly (as opposed to by passing the script file path to pythonw.exe). See eryksun's 2nd comment and its follow-ups below.
You can control which of the executables runs your script by default - such as when opened from Explorer - by choosing the right filename extension:
*.py files are by default associated (invoked) with python.exe
*.pyw files are by default associated (invoked) with pythonw.exe

If you don't want a terminal window to pop up when you run your program, use pythonw.exe;
Otherwise, use python.exe
Regarding the syntax error: print is now a function in 3.x
So use instead:
print("a")

See here: http://docs.python.org/using/windows.html
pythonw.exe "This suppresses the terminal window on startup."

If you're going to call a python script from some other process (say, from the command line), use pythonw.exe. Otherwise, your user will continuously see a cmd window launching the python process. It'll still run your script just the same, but it won't intrude on the user experience.
An example might be sending an email; python.exe will pop up a CLI window, send the email, then close the window. It'll appear as a quick flash, and can be considered somewhat annoying. pythonw.exe avoids this, but still sends the email.

I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.

In my experience the pythonw.exe is faster at least with using pygame.

Related

Python execute code in parent shell upon exit

I have a search program that helps users find files on their system. I would like to have it perform tasks, such as opening the file within editor or changing the parent shell directory to the parent folder of the file exiting my python program.
Right now I achieve this by running a bash wrapper that executes the commands the python program writes to the stdout. I was wondering if there was a way to do this without the wrapper.
Note:
subprocess and os commands create a subshell and do not alter the parent shell. This is an acceptable answer for opening a file in the editor, but not for moving the current working directory of the parent shell to the desired location on exit.
An acceptable alternative might be to open a subshell in a desired directory
example
#this opens a bash shell, but I can't send it to the right directory
subprocess.run("bash")
This, if doable, will require quite a hack. Because the PWD is passed from the shell into the subprocess - in this case, the Python process, as a subprocess owned variable, and changing it won't modify what is in the super program.
On Unix, maybe it is achievable by opening a detachable sub-process that will pipe keyboard strokes into the TTY after the main program exits - I find this the most likely to succeed than any other thing.

How to run python code from powershell with no command prompt showing?

I would like to be able to run a python script from a .ps1 file without the terminal window showing up to run the script. I would think that there is some extra command I can put at the end to make it run windowless, but I am not sure what it is.
The only code I have in the ps1 file is to execute the python script by linking the path.
I do not want to run the code some way else, it has to be from a ps1 script since I will be adding to it eventually to have more features. I also would rather not have to change the file to a .pyw if possible.
E:/script.py
*Note - I ran the file from a different drive this time, but I want it to be from E:/ like I have in my code.
What I don't want to show up:
In a comment you state:
im using run (WIN + R) and this command: powershell -w h iex (E:\a.ps1)
-w h is short for -WindowStyle Hidden
iex is short for Invoke-Expression, which is not needed here - and should generally be avoided: see this answer.
Note: While this does make the console window that the PowerShell session itself runs in invisible, the window becomes invisible only after briefly showing first.
To avoid this brief flashing of the console window, powershell.exe must be launched indirectly, namely via a GUI-subsystem application that launches it with a hidden window; the bottom section of this answer discusses options.
Also note that supporting this directly in the future is planned, but will likely only be implemented for the CLI of PowerShell (Core) 7+, pwsh.exe - see GitHub issue #3028.
With that out of the way:
Console applications (including .ps1 scripts) invoked directly from a hidden PowerShell session run hidden too, because they run directly in the hidden console window.
By contrast, any GUI applications or applications of either type invoked via Start-Process run visibly.
While you can generally use Start-Process -WindowStyle Hidden to run GUI applications invisibly as well, this, unfortunately, does not seem to work with .pyw files, i.e. pythonw.exe-launched scripts, which still run visibly.[1]
By default, .py files invoked directly execute via py.exe, which is a console application.
Strangely, your screen shot suggests that it is not in your case.
py.exe is normally just a launcher for the true console Python executable (allowing you to switch between v2 and v3 versions of Python with py -2 ... and py -3 ...), python.exe, so as a workaround you can try the following (use a full path to python.exe, if needed):
Modify your E:\a.ps1 script to explicitly invoke your .py script with python.exe:
python.exe E:\script.py
Then launch your invisible PowerShell session as before, except with improved syntax:
# Short for:
# powershell.exe -WindowStyle Hidden -File E:\a.ps1
powershell -w h -f E:\a.ps1
If that doesn't help, consider reinstalling Python.
[1] I'm guessing this is because the windows potentially created by the .pyw scripts themselves are unrelated to the (invisible) main window of the pythonw.exe GUI-subsystem executable.
Start-Process python -ArgumentList "python-script-file-path" -NoNewWindow
Lots of excellent info here.

Python.exe opens in a new console window

I used to run Python scripts from my Windows command line, and all the prints were printed in the same console. Now something happened on my machine (Windows 10), and when I launch a Python script from the command line (i.e. open a Command Prompt and run python <my_script.py>), Windows opens a new window (titled with the absolute path of python.exe). This windows closes automatically at the end of the execution, so that I can't see the output.
How do I go back to printing output in the same command prompt window from which I run the script?
Not sure how useful this will be but I had this same problem, found this thread, and realized that the new console window was opening up when I omitted 'python' from the command.
>python myscript.py
shows the output right in the terminal where I typed the command, but
>myscript.py
opens the new console window and closes it immediately after the script runs.
It's odd but it very likely a windows setup issue as python is an exe. If memory serves windows will spawn on a > run command so checking the way python is booting will help.
Unfortunately it could be a range of issues, so some steps towards victory:
What happen when you just type python into the cmd? If it simply starts the input >>> - it means your python setup is fine. If a cmd window spawns and disappears it may be a windows permissions issue.
Try running your script with -i flag: python -i script.py. This drops you into the repl when the app completes - displaying your output.
Ensure you're using the native flavour of the cmd to test. Ensuring any command app or IDE isn't injecting a start command or weird /K (spawn new window) flag.
Hope it helps.
In my computer this was caused by Windows not knowing what program a .py file was associated with. I solved this by going to:
Control Panel -> Programs -> Default Programs -> Associate a file type or protocol with a program (Scroll down) and choose "Choose default apps by file type" Scroll down until you see ".py" and choose the correct
Python interpreter.
Simply: last row on the end of your program maybe this:
input("\nIf you whish end the program press any key ...")
...and your program wait for the key and you see your outcome

Python script displays output in command window but nothing shows in Windows

I've written a script that works great at a command prompt, but it only displays the last line if I double click on the script.py icon on my desktop.
The function in the script runs perfectly but once it finds a match it's supposed to display the output on the screen. At the end, I have an os.pause statement and THAT displays when the script is done, but nothing else displays on the screen.
I AM executing it using pythonw.exe. What else should I check?
Thank you.
pythonw supresses the console window that is created when a python script is executed. Its intended for programs that open their own GUI. Without pythonw, a python gui app would have its regular windows plus an extra console floating around. I'm not sure what pythonw does to your stdout, but os.isatty() returns False and I assume stdout/err are just dumped into oblivion. If you run a DOS command like os.system("pause"), Windows creates a new console window for that command only. That's what you see on the screen.
If you want to see your script output, you should either run with python.exe and add an input prompt at the end of the script as suggested by #GaryWalker, or use a gui toolkit like tcl/tk, Qt or wxPython.
I've used a script like before and it seemed ok to me
print("Hello world")
input("Press return to exit")

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.
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.

Categories