sample.py is an existing python file.
Command to run that python file :
>>> python sample.py
Error message:
SyntaxError: invalid syntax
How to create and run a python file in a Python 2.7.14 shell.
sample.py is an existing python file.
Command to run that python file :
>>> python sample.py
Error message:
SyntaxError: invalid syntax
How to create and run a python file in a Python 2.7.14 shell.
If you are running this with IDLE
Go to file or run and choose the py file.
Your issue is you are trying to run it in the repl.
If you want to run a Python file, you have to run it outside of the Python's REPL.
Open CMD or bash depending on your OS, cd
to your python file's directory, then python sample.py
.
This could be accomplished using the exec
function. Assuming that sample.py
has a single print "hello world"
statement:
Example
>>> file = open('sample.py','r')
>>> exec(file.read())
hello world
You can read more about exec()
and how to use it here: https://docs.python.org/3/library/functions.html#exec
This must be happening because your are trying python sample.py
inside python shell, this would result in error because you are already inside python shell. Correct syntax in this case would be
exec(open("sample.py").read())
If you want to use python sample.py
then this syntax will work in terminal of your OS.
if you are using linux follow the below mentioned steps
if you are using windows follow the below mentioned steps
Solution 1: [From within your interactive shell]
If you want to execute a python within your interactive shell (as you are now, judging from your >>>) you can use the %run
function. Assuming your file sample.py is in the same directore as where you are running the interactive shell.
Example:
>>> %run ./sample.py
(This assumes your script is located in the same directory where your interactive terminal is running. If not, see https://stackoverflow.com/a/28462540/9216538 on how to change the current directory).
Solution 2: [From the command line in your normal terminal]
The standard option is to do this directly from the normal command line in your terminal. Open a regular terminal. Go to the directory where your python file is located with cd path-to-file
.
Example: [run this in your normal terminal]
python sample.py