Reputation: 89
I am new to python, just got the learning python book and got stuck with the spam.py in the command line. The book says to make a file named spam.py and then ask python to run this by typing %python spam.py I have added the python to my PATH as it was C:\Python27 so I can call Python in the Windows CMD, but this just will not run. The error I receive is
>>>python spam.py
File "<stdin>", line 1
python spam.py
^
SyntaxError: invalid syntax
I appreciate any help that you can give.
Upvotes: 1
Views: 3313
Reputation: 81
If for example, your file is in G: drive, type this in cmd:
python G:/myfile.py
Basically, type in the path. Just doing "cd" won't work in Python
Upvotes: 0
Reputation: 882078
Your problem is that you're trying to run your code from within the Python interpreter itself (the >>>
prompt is the giveaway here since that's the Python prompt).
Exit from the interpreter (with CTRL-Z and ENTER for Windows) and run it from cmd.exe
(the c:\>
is the prompt in the example below):
c:\> python spam.py
From within the interpreter, you can also run an external file with:
execfile('spam.py')
Upvotes: 5
Reputation: 80
In order to run a python program you have to run program in Command Line not in Python Interpreter
(press Windows Sign + R
and type cmd.exe
)
Moreover you have to remember to be exactly in the directory where your file is saved, e.g.:
If the file file is C:\Python27\spam.py
you have to be in C:\Python27
.
To change the directory:
dir
to display the folders and files in current placecd
to change your directory (e.g. C:\Python27\>cd Spam
moves you to C:\Python27\Spam
Tab
key to autocomplete names of the commands, folders and filesAs you said you have added Python to PATH and followed my instructions, the statement below should work perfectly
python spam.py
Hope I could help.
Upvotes: 0
Reputation: 853
You are trying to execute Python script file within the interpreter. Come out from the Python interpreter by pressing CTRL+Z and then ENTER key. Then execute with the command :
Say, C:/> python spam.py
Upvotes: 0
Reputation: 80
Could you post the code from spam.py
...
You seem to be trying to run the spam.py from the Python interpreter. Go to where the file is in Windows Explorer and launch it from there, using the C:\Python2.7\python.exe CLI.
By the way, since you didn't understand the syntax error warning, please see:
Upvotes: 0