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?
Related
I can change the console title form a python program using ctypes.windll.kernel32.SetConsoleTitleW(some_new_title) but as soon as the program exits (or crashes) the title reverts to whatever it was before. Is there some way to make the new title stay even after the program exits? The reason I want this is because I have quite a lot of different python scripts running on different consoles and I want to be able to quickly identify them by name in my taskbar. This works perfectly while the programs are actually running, but if a few of them either finish or crash then I have a collection of console titles in my taskbar which are all identical.
Thanks to the clue from #Jon Clements...
Instead of launching my python script with this:
python myscript.py
I write a batch file mypy.bat which contains...
title %*
python %*
Then I run my script with:
mypy myscript.py
The name of the window remains as "myscript.py" even after the script exits.
I just started a python bootcamp and am using Microsoft Visual Studio Code (latest version with Python 3.10.5) but have a couple of questions. (apologies for the long post)
I have the following code:
def weather_condition(temperature):
if temperature > 7:
return "Warm"
else:
return "Cold"
input("What temperature: ")
To my knowledge there are three options to run the code
Right mouse click and 'run python file in terminal
Select lines and press SHIFT + ENTER
RUN (with or without debugging)
However even though the script is the same, each choice shows a complete different result in the terminal.
If I choose to run the python file, it shows the following error in the terminal:
terminal error message
>>> & C:/Users/..../AppData/Local/Microsoft/WindowsApps/python3.10.exe d:/..../_SCRIPTING_/Python/Python001/user_input2.py
File "<stdin>", line 1
& C:/Users/fine/AppData/Local/Microsoft/WindowsApps/python3.10.exe d:/..../_SCRIPTING_/Python/Python001/user_input2.py
^
SyntaxError: invalid syntax
If I choose select lines (same lines used as #1),
selected lines
it runs the script but it displays the entire script run process in the terminal (which doesnt happen on the teacher's visual code:
mine:
>>> def weather_condition(temperature):
... if temperature > 7:
... return "Warm"
... else:
... return "Cold"
...
>>> input("What temperature: ")
What temperature:
teachers:
teacher's screen
And last but not least is the Run script (with or without debug).
debug run
Which opens a completely new Python 'debug' terminal. Here the script runs normally (it seems) and looks more like the teacher's version although his screen doesn't show 'debug' or the small toolbar
small toolbar
anywhere in his visual code.
A. So what is the difference between each of the choices?
B. Which of the 3 should I be using?
C. Why does the first option give an error even though the script is written correctly?
The three options you mention are all specific to VSCode, but you're right that they are intended to give you different ways to run a script.
To answer your questions:
A. So what is the difference between each of the choices?
The first option attempts to start Python in your terminal in VSCode, running a command like:
& "C:/Program Files/Python310/python.exe" c:/project/hello.py
The error message you are seeing is because in your terminal, Python was already running and VSCode just copies and pastes the above into the terminal, expecting it to land on a waiting terminal prompt, not on the Python interactive prompt. If you ran exit() first, to close Python and return to the terminal prompt, and then tried again, it would work.
What the command means is to start that version of Python, running your script, in the current working directory of the terminal, in the current environment of the terminal. (in the background, returning control to you, hence the &)
The second option does something similar, but instead of issuing the command above, just puts everything you selected on the clipboard and pastes it into the terminal. If that happens to be running Python on the interactive prompt, and the text selected is actually Python code, your script may work (depending on the code, and what was run before). If it was sitting on the terminal prompt, it won't because Windows, Linux or Mac OS doesn't understand Python without an interpreter.
The third option is very similar to the first, but instead of just dumping the simple run command in the terminal, it instead adds a few more commands, changing drive and directory and then trying to start the script. It still tries to use the active terminal for it though and it will fail (just as the first option) if Python happened to be running there already.
So, the 1st and 3rd are very similar, but completely different from the 2nd, which is trying to paste Python code instead of terminal commands.
B. Which of the 3 should I be using?
Depends on what you need. If you have a few lines of code you just want to see the effect of, you can use the 2nd method, assuming the lines of code will work in context of what you may have run before.
If you just want to run a script, it depends on where it needs to be run. VSCode gives you some more options to set up your environment for the script to run successfully, but it doesn't give you as much control as something like PyCharm (then again, it's also a lot smaller and quicker to start up than PyCharm and has fewer confusing complicated controls - it's a matter of taste and need).
C. Why does the first option give an error even though the script is written correctly?
As indicated above, it only generates that error when the terminal has an interactive Python session running (you can tell from the >>> prompt). The third one would give you a similar error if you tried it in that setting.
Similarly, the second option will cause problems if you don't have an interactive session started (i.e. running some python.exe).
I have configured PyCharm (or, to be more precise, the selected interpreter) to leave the python console open when a program execution has finished. I find it very comfortable to debug and watch things like in RStudio: Marking them in the source window and hitting Control+Enter (or 'any control like button'+Enter). So after discovering the 'Execute Selection in Console' Command I was able to run stuff interactively in the console the script was ran in. However, there are two issues with that:
1) whenever I do this for the first time, PyCharm asks me in which console I want to execute the code. Then of course I always select 'the console in which the script was run'.
2) Even though I select the console the script ran in, the marked code is always executed in a new python shell (so it forgets about all the pandas settings for example, i.e. it only prints two columns or so)
Can one somehow make it run the marked code always in the console the script runs in?
See the following screenshots:
1) run the script
2) change some of the code (i.e. c becomes aa+2*b instead of a+b), mark it and let it run in the console:
3) PyCharm asks me about 'which console to run the marked code in'???
Oopsie, I found the problem. In the run configuration I did put an argument to the python interpreter (namely '-i' which causes the interpreter to leave the session open even though the script has terminated exactly as I wanted it) but the solution was to let PyCharm do that for you by selecting the 'Run with python console' option:
Now every time I run the script it is run in the same console and I can execute code interactively and PyCharm does not ask me anymore in which console I want it to run.
I'm trying out some data science tutorials with python and can't get print to, well, print! when I run a .py in windows command shell or powershell. Print does work when I use the interpreter, but I have to type it in line by line (I'm not seeing how to run a .py as a file in the interpreter). I'm attaching snips of the file, and a snip of me running in the interpreter. I tried to attach snips of what happens when I run in command shell and powershell, but apparently I need at least 10 reputation points before I can post more than 2 links. Admittedly, those snips weren't interesting; there is no error and nothing printed. It just runs and returns to the prompt.
Also, as a test, I saved a .py file that simply does print ("Hello") and it does print correctly in windows command prompt and powershell.
Thanks in advance for any help!
Casie
PY script
Snip From Python Shell
Is that image from the IDLE console? To run the script you are editing, use menu Run > Run Module, or F5. Every python GUIs has an equivalent feature.
To run an arbitrary script from inside the commandline interpreter, say mywork.py: As long as it's in the working directory that you were in when you started the interpreter, you run it (once) by typing import mywork. (As you can see, its name must be a python identifier.)
Edit: You'd get to the bottom of this a lot quicker if you'd put print("Hello, world") in a script by itself and run it. From over here it looks like it would print just fine, proving there's nothing wrong with your python interpreter.
Your script has a bug, though: As soon as you enter the function random_kid(), you leave it again since you return a value on the first line. All those print statements are never executed. Why you think it works differently with %run I can't say, but for sure this function cannot print any output.
This question already has answers here:
How do I run a Python program in the Command Prompt in Windows 7?
(24 answers)
Closed 7 years ago.
So I'm an extreme beginner to programming, just starting the Python class on Coursera. Using Python 2.7.10
Anyway, I made a simple print statement script in Notepad++
print "Hello World"
and saved as a python file on my desktop
newprog.py
However when I try to run it a cmd window appears and disappears and I'm not quite sure whats wrong.
The other question that this was linked as a duplicate to is about accessing python through the command prompt, which I don't have a problem with. From answers given it is now apparent to me that my dilemma was due to an erroneous belief that the interpreter would remain open after running whatever script I wrote.
Sounds like your program simply opened, ran and exited. So nothing was wrong, it just all happened a bit quick for you to see it.
You should run it from a command prompt or get an IDE like Pycharm, which will allow you to both write and run your script in one program.
To run from command prompt, use either Windows Key + R and type 'cmd' or click start and type 'cmd' into search box. Then you can drag your script to the command prompt window and press Enter to run it.
If you wanted to run it by double click, you'd need something to stop it from finishing until you'd read the message. To achieve this you can use the raw_input function, which waits for user input.
So your script would then look like
print "Hello World"
raw_input("Press Enter to exit")
Then you could double click and press enter when you are ready to exit.
Go to the command prompt window
python
then type in
execfile('path to newfile.py here')
Your file will now be executed
I'm running python 3.4.3. But it should be the same, I hope.
Go go "..\PythonXX\Lib\idlelib" and look for idle.pyw NOT idle.py and using the you're able to execute simple one line commands like the one you have up there.
From that you can also create a new file and do more complicated stuff.
If you create a shortcut to your desktop, you'll be able to access it easier.
Let me know if it helps, or at least correct path.
Your script is probably working and then finishing, the result is shown but not for long. I recommend opening the console and running your script from there, or you could use a simple batch file to run python scripts and then wait for a key press.
To open the console you can use the Windows key along the R key, Win-R (to run a new process) and write cmd, or you look for cmd in your Window's start menu.
With the console opened, you must locate the path where your script is, you can use the cd (Change Directory) to get there, for example:
cd C:\Users\your_name\Desktop
and then write:
python newprog.py
to run your script.
Another option is to use this simple batch file (save it as python34.bat or similar, but the extension must be .bat, put it wherever you like):
#ECHO OFF
C:\Python34\python.exe %*
pause
#ECHO ON
And then use that to run your scripts by right clicking a python script file, open with (run with) and use this batch script as default (if you want). Also, if you have another version of Python, or is installed elsewhere, you must change the "C:\Python34\" part.
This is a computer we're talking about here. It might take you triple the time it takes a computer to multiple two numbers for example. With this notion in mind, the computer quickly prints then exits.
raw_input() # at the end of script wait for user to supply input, delaying script exit