3

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.

vasanths294
  • 1,457
  • 2
  • 13
  • 29
  • I assume you are trying to run a python file from the terminal. If that is the case, you should type the command at the command line: `$ python sample.py`. I think the problem is that you first dropped to the Python REPL and tried to execute the command. – sudormrfbin Jan 14 '18 at 17:22

6 Answers6

1

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.

Mike Tung
  • 4,735
  • 1
  • 17
  • 24
1

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.

yanxun
  • 566
  • 2
  • 10
1

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

Spence Wetjen
  • 199
  • 1
  • 9
1

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.

akshif
  • 191
  • 1
  • 1
  • 10
1

if you are using linux follow the below mentioned steps steps in Linux step 1 step 2 step 3

if you are using windows follow the below mentioned steps steps in windows step 1

K.Vani
  • 72
  • 4
1

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