python vs pythonw [duplicate] - 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

I want to display the results from other applications(LabVIEW) in the CMD window

I am programming python code in LabVIEW now. I want to display my results in CMD console, but I don't know how to connect them to cmd console. My bielf code is as follows.
import os
os.system("start /wait cmd")
print("I want to display my results to the CMD window")
This ensures that only the cmd window appears and no print function results appear. Help me
There are two types of programs. Console and graphical. The difference is a flag in the file header. If set as non graphical it will open with an automatic console unless it's parent program is also non graphical then it will inherit it's parent's console. If set as graphical absolutely nothing special happens.
Any program can show windows and any program can start a new console or attach to any existing console.
Your question is a bit weird. CMD is a console program. There is nothing special about it. You don't need CMD to run in a console.
So it depends on how you compile. With a graphical interpreter or a console interpreter.
However you are starting CMD disconnected from your program, which it would be if your program isn't a console program anyway, by using the START command which starts programs in unusual ways.
See start /?. See https://learn.microsoft.com/en-us/windows/console/character-mode-applications.
PS You write to a console not to CMD.

Running a python script in a Windows 10 powershell

I have a little python script that takes a single filename as a command line argument and writes a converted file. Not rocket science, it's 10s of lines long.
I can run that on windows from a cmd prompt simply by typing the name of the script. So for example:
C:\> CD \wheremyscriptis
C:\wheremyscriptis> myscript.py
and it runs fine. Without any arguments it spits out a little Usage message. Quite conventional.
Now we're using Powershell more and more and the first thing I notice in powershell is it won't run at all without an explicit directory, so in the above example I'd need to type .\myscript.py.
That's odd but you could get used to it, not a crisis.
But what happens now is the script runs in another window, which flashes up and disappears before youc an read the usage message.
Given the behavior is inconsistent across these contexts, what can we do inside the script to make the powershell context more usable. Is there a way to detect if we're running in some window that powershell threw up (which is itself weird) and then if so, pause before exiting to give a user a chance to read the usage message before the window disappears?

.pyw and pythonw does not run under Windows 7

Running a simple .py or .pyw python file causes python.exe to show up under Task Manager.
python myApp.py
python myApp.pyw
However when we try to run it without using the console, the script does not appear to run, nor does python.exe or pythonw.exe appears under Task Manager
pythonw myApp.pyw
pythonw myApp.py
How do we troubleshoot the problem? The system is running Python 2.7.8 x64.
tl;dr
To troubleshoot, use output redirection on invocation:
pythonw myApp.py 1>stdout.txt 2>stderr.txt
This will capture stdout output, such as from print(), in file stdout.txt, and stderr output (such as from unhandled exceptions), in file stderr.txt; from PowerShell, use
cmd /c pythonw myApp.py 1>stdout.txt 2>stderr.txt).
Note that the very act of redirecting stdout may actually make your script work again, if the only reason for its failure with pythonw was the use of print (in Python 2.x - see below).
Caveat: This output redirection technique seemingly does not work when invoking *.pyw scripts directly (as opposed to by passing the script file path to pythonw.exe). Do let me know if you know why and/or if it does work for you.
To fix your script:
Place the following at the top of any Python 2.x or 3.x script that you want to run with pythonw.exe:
import sys, os
if sys.executable.endswith("pythonw.exe"):
sys.stdout = open(os.devnull, "w");
sys.stderr = open(os.path.join(os.getenv("TEMP"), "stderr-"+os.path.basename(sys.argv[0])), "w")
This ensures the following when a script is run with pythonw.exe:
print() calls and explicit calls to sys.stdout() are effectively ignored (are no-ops).
Stderr output, including from an unhandled fatal exception, is sent to file
%TEMP%\stderr-<scriptFileName>; %TEMP% is a standard Windows environment variable that points to the current user's folder for temporary files.
In other words: With the above code in place, check file %TEMP%\stderr-<scriptFileName> after your script has failed silently when invoked with pythonw.exe.
For an explanation, read on.
On Windows, pythonw.exe is for launching GUI/no-UI-at-all scripts, which means that the
standard in- and output streams - sys.stdin, sys.stdout, sys.stderr are NOT available.
This has two nasty side effects:
Using print() - which targets sys.stdout by default - causes an exception in Python 2.x.
This problem has been fixed in Python 3.x.
Any unhandled exception - including one triggered by print() in 2.x - causes the script to abort silently.
Exception error messages go to sys.stderr by default, which is the very thing not available in this scenario.
The above code fixes these problems by:
sending stdout output to the null device, effectively ignoring any attempt to output to sys.stdout - whether explicitly, or implicitly via print().
sending all stderr output to a temporary file.
Differences between Python 2.x and Python 3.x:
When a script is run with pythonw.exe, sys.stdin, sys.stdout, and sys.stderr:
in Python 2.x: have invalid file descriptors
The eventual result when trying to write to sys.stdout or sys.stderr is the following exception: IOError: [Errno 9] Bad file descriptor
Pitfall: Due to output buffering, this exception may not surface until you've output, say, 4K bytes; you can provoke it instantly by invoking pythonw.exe with -u (for unbuffered output).
print() blindly tries to sys.stdout (by default), so it provokes this exception sooner or later.
in Python 3.x: are set to None
This is complemented with the 3.x print() function performing a no-op (doing nothing) when it finds that sys.stdout is None, so that print() statements can by default safely be used - they'll simply be ignored when run with pythonw.exe
However, it follows that trying to use sys.stdout.write() and sys.stderr.write() still results in an exception.
See here for more background.
Try adding the line import sys; sys.stderr = open("errlog.txt", "w") to the start of myApp.py. Then look in errlog.txt for a traceback or any other error messages.
I faced the same problem on a script of my own and found that when adding the output from Ross' answer the script would actually run.
It appears that for some reason that redirecting output fixes the problem. Since I'm not interested in writing the output to disk I've instead written it to /dev/null (or the platform equivalent) with:
if ( sys.platform == 'win32' and sys.executable.split( '\\' )[-1] == 'pythonw.exe'):
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w')
The if statement ensures it only happens when the script is launched from pythonw.exe. I'm not sure if it is related but it was important to do this before other imports (including e.g. import logging).
I was having similar problem.
After debugging step by step by writing to a log file, I discovered that pythonw.exe crashed after a statement that tried to use the call: sys.stdout.write(). It turns out, when run with pythonw.exe, sys.stdout is None.
If you are using functions of sys.stdout/stderr/stdin, and intend to use your program with pythonw.exe, adding a check for "None" is a good idea.
Im not sure I understand your problem but I think this is what you need to know
you need to right click on a py or pyw file and select open with ... find python.exe (probably C:\Python27\python.exe) .. check the box that says always open ... now you can just double click it if you want to run it
(usually the installer sets this up for you ...)
This is an old answer, but I want to leave my solution here also:
Open CMD (with elevated privileges or not - depends on your needs)
Change to directory of .py / .pyw script - this is important
Run pythonw with script as argument
cd E:\my\script\folder\
pythonw script.py
I had a similar problem after an upgrade to my computer RAM. Turns out I had to reinstall Pillow (library used for image processing). So make sure it is installed and if it's not, install it using "pip install Pillow" in cmd.

why is the python GUI interface fleeting

#coding=utf-8
import wx
class App(wx.App):
def OnInit(self):
frame=wx.Frame(parent=None,title='Bare')
frame.Show()
return Ture
app=App()
app.MainLoop()
runs OK! but the GUI interface is fleeting, just leaving the CMD console in the screen.
a newer for python ,why the outcome of the GUI interface fleeting?
environment:Gvim+WIN7+PYTHON2.7
First, according to help :! command of vim:
:!{cmd} Execute {cmd} with the shell.
vim cause the cmd shell to be executed.
Second, according to Using Python on Windows - Executing scripts:
Python scripts (files with the extension .py) will be executed by
python.exe by default. This executable opens a terminal, which stays
open even if the program uses a GUI. If you do not want this to
happen, use the extension .pyw which will cause the script to be
executed by pythonw.exe by default (both executables are located in
the top-level of your Python installation directory). This suppresses
the terminal window on startup.
So, if you want run the GUI program without cmd console, run the program outside the vim using pythonw.exe. For instance, save the file with .pyw extension, and double click the file.
It is fleeting because you have a NameError in your code. You should be returning True, not Ture, which is undefined.
I am surprised you still see the console window though. If that stays up though, it should be showing the traceback.

possible to run idlex without a heartbeat (i want to minimize number of windows)

when i start idlex from a command prompt (Windows), i lose my prompt to the new process until i close idlex.
F:\>c:\Python27\Scripts\idlex.py
[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing c:\users\myname\appdata\local\temp\tmpch1j8w.json
heartbeat: 1.0
i want to see only the idlex gui and not this heartbeat info. is this possible ?
initially i thought running with '-n' would work, but the result is not what i thought i might be.
You can get your console back by launching the program with pythonw instead of python. The pythonw interpreter doesn't use the standard input and output file handles, so it doesn't need a console window to be open for those.
The best way to get a script to always use pythonw is to rename its extension from .py to .pyw. That should also work if you launch it from an explorer window or shortcut, rather than from the console directly.

Categories

Resources