Running Python Programs from a Terminal - python

I am working on page 16, chapter 1, in the book "Python Crash Course" by Eric Matthes. I am trying to run my hello_world.py python program from my Windows terminal.
The directions say to:
Open a new terminal window and issue the following commands to run hello_world.py:
C:\> **cd Desktop\python_work**
C:\Desktop\python_work> **dir**
hello_world.py
C:\Desktop\python_work> **python hello_world.py**
Hello Python world!
python_work is my python work folder on my desktop. In my Windows terminal, I have tried entering the code with and without the unbolded C:\>. It has given me an error message: The system cannot find the path specified. I'm probably doing something wrong, but I don't know what's wrong.

Assuming your getting your error when you execute "python hello_world.py", Python might not be installed correctly. More likely is that you are not in the correct directory. Do the following commands:
cd "C:\Desktop\python_work"
python hello_world.py
If that does not work, I can only assume one of two things:
Either the folder or the .py file is not named what you think it is and you should rename whichever one, or python is not installed correctly and you should reinstall it.

use
cd C:\Desktop\python_work
to change your working directory and then type
hello_world.py
to launch your program or if that doesn't work try
python hello_world.py
alternatively (what I do), assuming the first option worked, you can create a .bat file with the following code.
#echo off
"%~dp0\hello_world.py" %*
pause
and then just put that bat file in the same folder as "hello_world.py" and when you run the bat file it will launch the script. :)

Related

Opening Python script mode on a MacBook

I have a MacBook air and have tried opening Python in terminal but when I open it, it opens Python interactive mode. Does anyone know how to open Python script mode please.
I’ve tried typing in things such as Python or Python 3 like safari suggests but that didn’t work.
There is no 'script mode'. You can create a Python script using TextEdit or another editor, save it as myfile.py, and then run it with python myfile.py.
for running what you are calling 'script version' of python you should choose a python file to run and make sure is written in the same or in a compatible version to the python you are running it with (python2, python3)
For running an example script:
python main.py
You need to be in the directory containing the file so make sure you are there before running the command. Using python runs the first version of python you installed, so if you want to use an other you should use:
python2 main.py
python3 main.py
etc
Assuming you've stored your script in a file named itworks.py, the simplest thing is to type the command python3 itworks.py in a terminal window after you've moved to the directory containing the script. Alternatively, you can type python3 followed by a space, then locate your python script in the Finder and drag and drop it into the terminal. This will expand to the full path to the file, allowing you to run a script located elsewhere than your current directory. Don't forget to press return...
In older versions of MacOS you could say python, but that uses python 2 which is no longer supported so you should go with python3 for any new development. (With MacOS Ventura, python 2 seems to have been removed.)
If you have multiple versions of python, you can use the command which -a python3 (or python) to see all versions on your PATH, and the order in which they will be found. PATH works on a first-come-first-served basis, but you can override by using the fully qualified path name to an alternative python.
Yet another solution, for when you want a more permanent script you will use many times in the future, is to use a "shebang" line as the first line of your script. For example, I wrote the following tiny demo:
#!/usr/bin/env python3
print('It works!')
The first line says to parse this script with the first python3 interpreter found in your current environment's PATH. You could replace that with an explicit path such as #!/opt/homebrew/bin/python3. Now make the script executable: chmod a+x itworks.py. You can now run the script from the current directory by typing ./itworks.py. (The leading ./ tells your shell you know it's in the current directory, and is intended as protection against trojan horse scripts.) If you want to be able to use the now-executable script from anywhere, add it to a directory on your path such as /usr/local/bin, and you'll be able to run it by just typing itworks.py.

Trying to run Python program from command prompt

Path must be messed up and I can't fix it.
In the command prompt I am trying to open and run a python program that I made in IDLE. I am running Python 3.8.5. According to Automate the Boring Stuff, I should just be able to do:
py birthdays.py
But when I do that I get:
C:\Users\name\AppData\Local\Programs\Python\Python38-32\python.exe: can't open file 'birtdays.py': [Errno 2] No such file or directory
All of my scripts are located in: C:\Users\henri\AppData\Local\Programs\Python\Python38-32.
The only thing that I could think of is that it is going one step too far and searching in python.exe instead of just Python38-32. But Ii'm not even sure it works like that.
I tried to add the exact path using:
set PATH=%PATH%;C:\Users\name\AppData\Local\Programs\Python\Python38-32
But when I do this and press enter nothing happens.
when I want to use CMD to run python scripts, I just use
cd\
to back the main root of drive C. then use
cd folderAddress
for several time until to reach the exact scrip containing folder. Finally, I type
python scriptName.py
In your command prompt type python.The output should be python 3.** (depending on your python version).
If you see the python version it's working fine. In command prompt navigate to the folder that you have your python file using cmd command. then type
python birtdays.py
Don't forget the space after python.

Can't run Python file via Command Prompt, File is not defined error

I am new to Python and currently doing a basic python course to learn. I have been running code all day via the Command Prompt and it has been working fine. For some reason though it has stopped working and python files I try to run are returning the following error:
Traceback (most recent call last):
File "", line 1, in
NameError: name 'hello' is not defined
As per the screen shot and the numbers on it, I performed the following steps in an attempt to run the file:
change to the folder where file is saved
run 'dir' to list all files. I am trying to run 'hello.py'. This contains the code: print('hello simon!')
I can run the file by just typing hello.py into the command prompt, this works ok
I can also run with: python hello.py - this works ok
when I activate Python by typing Python --> Enter, this starts the interpreter ok. However if I then try to run by typing hello.py I get the error message.
This has worked ok all day, I have not changed anything on my PC (to the best of my knowledge!) but just started to get this error a few hours ago. I have looked all over the internet for solution but found nothing. I have uninstalled and re-installed Python, restarted etc... all to no avail.
I am running Python 3.6.5 on a Windows 7 64 bit PC.
It won't let me attach a picture so here is link to screenshot of Command Prompt and error: https://i.stack.imgur.com/BBUe5.jpg
I hope someone can help me with this please
Thankyou
You are not supposed to execute hello.py in the Python Interpreter. It won't work. When you type in python and hit Enter in your Command Prompt, Just type this,
>>> print('hello simon!')
And hit Enter, it would definitely work. Because the interpreter is supposed to execute a code line by line. So if you want to run a Python Script then do not execute it in the Interpreter.
The problem is that when you write python (alone), the command line calls python shell and the following commands are run inside the python shell and not in the command line anymore. Calling a script from the shell has a different format (look it up). You can enter exit() to exit the shell back to command line again
What you are trying to achieve is you are running Hello.py inside Python.
Not with Python.
You need to run Hello.py with Python. As python is interpreter over here.
>>>python
means you are going inside python shell
>>>print('hello simon!')
Is equivalent to your program.
You are running your Python Script as you should and it's working. If you added Python to your path you can run Script you only need to call the Script "hello.py". If you have more than one intepreter, or you didn't added it to your path then you can call it like this "C:\path\to\python\interpretet\pythonxxx.exe" "c:\path\to\python\script.py" you can enven pass arguments to it "C:\path\to\python\interpretet\pythonxxx.exe" "c:\path\to\python\script.py" --argument
When you type python in a shell, then interactive mode is activated. This is like a shell where you type commands and got interpreted right away, in the same way as cmd and powershell works, but for python. This way you can test snippets, or just do simple stuff overly complicated like this
import os
ls = os.listdir(os.path.abspath('c:/'))
def print_dir():
for file in ls:
print(file)
Wich in cmd would be dir c:\ or in powershell ls c:\. The point is that you can test libraries, explore objects, replace the shell or just have fun.

Is there a way to shorten command line commands to open Python scripts?

I'd like to know if there is a way to shorten what must be written on the cmd.exe command line to run Python programs. As it is, I have a program called Calculator.py and if I wanted to run that I would have to write:
python.exe C:\Users\user_name\restofdirectory\Calculator.py
Basically I want to know if I could make the 'Python' folder on my computer default so I could just type python.exe Calculator.py or some other similarly short way of doing it so I didn't have to type the whole directory.
Create a cmd.exe shortcut somewhere handy (Desktop or whatever). Right Click, select properties. Under the Shortcut tab you'll have a "Start In" field. It'll be default to wherever your cmd.exe normally opens. But you can change it to any path you want (So set it to your python development folder)-- then opening that shortcut will always start cmd.exe in the python folder.
You don't need to type python.exe file.py --
Just type: python file.py
So in short, you'd click that shortcut and type python file.py and you are done.
If you have specific scripts you want to run frequently, you can create a cmd.exe shortcut for each one. Set the Start In path to their folder. Then update the link to cmd.exe like this:
c:\path\to\cmd.exe /k python file.py
That will open a cmd prompt and automatically run that specific script
Yes, you can cd into the folder first.
If python is in your default path you can create a folder and put all your python scripts in it. Then cd into that folder and type python Calculator.py. To test if python is in your path simply open up a cmd and type cd \ (which in your case should change your working directory to C:\) then type python. If you get an error saying the command python cannot be found then you have to add python to your path. Other wise you should be able to run cd C:\Users\user_name\restofdirectory\ and then execute the script python Calculator.py
create an environment variable, say, PyPath = C:\Users\user_name\restofdirectory
then your line would be:
python.exe %PyPath%\Calculator.py
or you just cd to C:\Users\user_name\restofdirectory, and run
python.exe Calculator.py
Add Python to your path:
SET PATH=%PATH%;C:\Python27\bin
then you can call python like this:
python myapp.py
If you have the Python Launcher for Windows (comes with Python 3.3+) installed, then it gets even easier. You just need to put shebang in your code:
#! python
The first time you run your code, Windows will pop up a dialog and ask you what program to use to run the script. The Python Launcher should be listed. Just choose that and away you go. Here's a fun little script from the page I linked earlier:
#! python
import sys
sys.stdout.write("hello from Python %s\n" % (sys.version,))
Once my Windows 7 box had the launcher installed and I told it what program to run, I could just call my script from cmd.exe like this:
my_script.py
Note: If you have a version of Python older than 3.3, you can download the installer here

starting Python IDLE from command line to edit scripts

I've tried many variations of this command: idle.py -e filepath, but it simply starts IDLE like normal, not opening any extra windows for editing, and not throwing any errors.
So how can I do the equivalent of opening IDLE, file>open>filepath via the command line (or perhaps even a Python module)?
You need to do as stated in the main.py file of the idelib folder (C:\Python33\Lib\idlelib), at least on the python 3.3 version explains that:
IDLE main entry point
Run IDLE as python -m idlelib
So with python -m idlelib <script_to_edit> you will be able to open and edit the script with idle. I haven't checked with previous versions but it could be the same comand
This is also documented on the changelog of the version 3.3.3
Make a new text file, and put something like this in it:
C:\Python26\Lib\idlelib\idle.pyw "C:\file1.py" "C:\file2.py"
In your actual script, you'll replace "C:\file1.py" and "C:\file2.py" with your files' paths, save as a .bat, and then launch it. That should do what you want.
Please forgive me for bumping such an old thread, but I've been teaching myself linux and python with the help of the community, and was trying to figure out how to invoke IDLE2 and IDLE3 from the command line. I came across this post some of the solutions seemed a bit complicated for my application. Then it occurred to me that I could just put syslinks in the /usr/bin/ path for each.
sudo ln -s idle-python3.1 idle3
sudo ln -s idle-python2.6 idle2
to address the OP. From the directory the script is located, type:
idle3 abc123.py
or
idle2 abc123.py
I'm just so damned happy that I finally had a "light bulb" go off that I wasn't going to let a 2 year old post stop me from posting my solution.
Rarely the native os is useful. I created a 'win batch file, in the folder with my .py files:
start /MIN cmd /C c:\Python27\lib\idlelib\idle.py -e %1 %2 %3 %4 %5 %6
This can open up to six files from cmd line in one shot. Just type the name of the batch file, followed by from zero to six filenames. Also if one or more files you specify are not found, idle opens these as new document(s).
first make sure you have location of idle in path
I am using "python3.5".So mine looks like this:
C:\Program Files\Python35\Lib\idlelib.Yours may differ.
use this following command:idle -r file_name.py to run the file
or just idle file_name.py to edit
or start idle -r file_name.py ^&exit
you can just program in Python to edit your Python files. A simple example. say you want to search for a word and then replace it with something else.
import fileinput
import os
os.chdir( os.path.join("c:\\","path") )
for file in os.listdir("."):
for line in fileinput.input(file,inplace=0):
if "search word" in line :
line=line.replace("search word","new word")
print line
(use inplace=1 to do in place editing.). Then save and run the script as normal Python script using the interpreter.
Just add IDLE's path to your PATH environment variable.
For example I created an environment variable called IDLE_PATH and set the value to C:\Python27\Lib\idlelib
Then in my PATH variable I added ;%IDLE_PATH%; and open a new cmd prompt or in console2 just open a new tab and run idle <file_name> to open the file, you will be able to do this from any directory. In IPython console add an ! before the command, for example !idle test.py.
Congrates, Now you're a python pimp!
paste the idlelib to your system path or user path, environment variable.for example, like this
C:\Program Files\Python310\Lib\idlelib
then type idle in your command prompt. done.

Categories