Python.exe opens in a new console window - python

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

Related

How to make Windows execute my Python script files when I click them

I have made a Python program that uses output.to_csv('results.csv'). When I run it in Spyder it creates that CSV file. But when I double click on it nothing happens. Cmd appears and closes but nothing on the folder, no results.csv.
What am I missing? What more do I have to do?
Run the program from the command line itself instead of double-clicking the .py file.
I assume you are on Windows since you mention CMD. First, cd into the directory containing your program. Then, run python <program>.py or python3 <program>.py depending on your installation.
This time, you will see any output or error messages that appear in CMD without it immediately closing.
If the .csv file really exists, you should be able to go to your File Explorer and find the file at the top of the "Quick Access" section. Right-click the file and hover over "Open With >". Then select Notepad and a notepad will open up showing your results.
If you do not see the file, then try running your program on the command prompt (for Windows):
Press the windows key and type "cmd" in the search bar.
Choose "Command Prompt"
Go to the dir of your program using the cd command
Type python <program name>.py
If there are no errors, follow the steps in the first paragraph.
Ok i guess windows is not recommended at all for this type of tasks. I mean running something simple as create such file is like trying to kill the Lernaean Hydra.
What i did is i just runned it with anaconda prompt and it worked sweet! Thanks for help. Thanks to all!
PS: I'm seriously considering changing to Linux after this
For anyone having the same problem, but have anaconda installed. 1) Open Anaconda Prompt, 2) use cd (1 space) then adress of the folder which contains your py program (eg. cd C:\Users\Bernie\Desktop\tasos) and hit enter, 3) on the next line that appears type: python program_name.py, 4)Hit enter, 5)success!

Cannot run a Python file from cmd line

I have installed Python and written a program in Notepad++.
Now when I try to type the Python file name in the Run window, all that I see is a black window opening for a second and then closing.
I cant run the file at all, how can run this file?
Also I want to tell that I also tried to be in the same directory as a particular Python file but no success.
I assume you are running the script with command python file_name.py.
You can prevent closing of the cmd by getting a character from user.
use raw_input() function to get a character (which probably could be an enter).
It sounds like you are entering your script name directly into the Windows Run prompt (possibly Windows XP?). This will launch Python in a black command prompt window and run your script. As soon as the script finishes, the command prompt window will automatically close.
You have a number of alternatives:
First manually start a command prompt by just typing cmd in the Run window. From here you can change to the directory you want and run your Python script.
Create a Windows shortcut on the desktop. Right click on the desktop and select New > Shortcut. Here you can enter your script name as python -i script.py, and a name for the shortcut. After finishing, right click on your new shortcut on the desktop and select Properties, you can now specify the folder you want to run the script from. When the script completes, the Python shell will remain open until you exit it.
As you are using Notepad++, you could consider installing the Notepad++ NppExec plugin which would let you run your script inside Notepad++. The output would then be displayed in a console output window inside Notepad++.
As mentioned, you can add something to your script to stop it completing (and automatically closing the window), adding the line raw_input() to the last line in your script will cause the Window to stay open until Enter is pressed.
Try to open in Command Prompt instead of run window. The syntax is:
py filename.py
If it doesn't work, try to reconfigure Python. Did you set environment variables? If not, this could help you

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.

pythonw.exe or python.exe?

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.

Categories