I'm new to Python and I created my first piece of code which is simply
print('Hello World!')
and it works fine and I named it hello.py. When I try to open the file it says with "python hello.py"
I get an error message that says
File "hello.py", line 1
PYthon 3.4.4 (v3.3.3:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1.600 64 bit (AMD65)] on win32
SyntaxError: invalid syntax
I added Python to the PATH so I don't know what's the issue
You're not supposed to put those lines into your script. They come from the interpreter, giving information to you. You're only supposed to include in your script the commands that you want to give to the interpreter. In your case, your hello.py file should consist entirely of this:
print('Hello World!')
and nothing else.
Related
Using just notepad I typed out:
print ('hello world')
and saved it under ThisPC>windows(C:)>Users>me>Anaconda3 as:
first_program.py
Now I'm in Anaconda Prompt, I typed in Python and got back:
Python 3.7.4 (default, Aug 9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
But when I try to run the script I thought I made, by typing in (without quotes) "first_program.py" I get back an error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'first_program' is not defined
I have no clue what's causing it. So far I've tried changing the syntax of the script, like:
print 'hello world'
print "hello world"
print (hello world)
print ("hello world")
and other variations with the parentheses and keep getting the same error message.
Please help me understand what I'm doing wrong.
When you type in python in anaconda prompt, it launches the python interpreter. Any Python code written in this context while be read and executed.
When you type in "first_program.py" within the context of the interpreter, it will rightly raise a NameError as in the context of the interpreter, this reference does not exist.
However, if you were to simply type in the python command print('hello world') and hit enter, the interpreter will render the output correctly and print 'hello world' on your terminal.
To run the python script, simply open a terminal or Anaconda Prompt (navigate to the directory in which the python script resides) and run your script by typing either python first_program.py or first_program.py.
Assuming you're on the command line, and in the same directory as first_program.py
you can do:
python first_program.py
This will start python with your file as what you want it to run and then exit when it is complete.
There’s a project where I need to use both Python 3.3 and 2.7. I am trying to launch a script under Python 2.7 but it’s not working. Here is a simple example.
first.py
import subprocess
import sys
print('Inside first.py')
print(sys.version)
subprocess.Popen(["C:\Python27\ArcGISx6410.2\Python.exe", "second.py"])
second.py
import arcpy
print 'This is second.py'
This doesn’t work and the output is
Inside first.py
3.3.5 (v3.3.5:62cf4e77f785, Mar 9 2014, 10:35:05) [MSC v.1600 64 bit (AMD64)]
File "C:\Python33\lib\site.py", line 173
file=sys.stderr)
^
SyntaxError: invalid syntax
That’s the entire stack trace. If I were to replace C:\...Python.exe with notepad.exe then it works. I’m using Liclipse on Windows 7.
UPDATE: it appears different versions of Python are run, when from the command line python first.py is 3.3 but py first.py or just first.py then 2.7 is used.
Try:
import os
subprocess.Popen(["C:\\Python27\\ArcGISx6410.2\\Python.exe", "second.py"], env=dict(os.environ, PYTHONHOME="C:\\Python27\\ArcGISx6410.2"))
Python on Windows needs a little help sometimes to figure out which version of the standard library to use.
I am a new Python user and I have been working through a number of tutorials. This has included running some of the code from the Command Prompt. This worked fine when I first tested the code but for some reason it seems to have stopped working and I am now getting errors when using Input(). I have included the code below and the error message I am receiving.
Code:
import sys
print (sys.version)
print("hello world")
myName = input("What is your name?")
print(myName)
if (myName == "Matt"):
print("Matt is great!")
elif (myName == "Bob"):
print("Bob is ok")
else:
print("Hello world")
input("Press enter to continue")
Error Message:
C:\Users\matt.xxxx>cd C:\Python34\Scripts\Projects
C:\Python34\Scripts\Projects>helloworld.py
2.7.7 (default, Jun 1 2014, 14:21:57) [MSC v.1500 64 bit (AMD64)]
hello world
What is your name?Matt
Traceback (most recent call last):
File "C:\Python34\Scripts\Projects\helloworld.py", line 6, in <module>
myName = input("What is your name?")
File "<string>", line 1, in <module>
NameError: name 'Matt' is not defined
C:\Python34\Scripts\Projects>
I know this can occur when using older versions of python, however I have checked and I am fairly sure I am using version 3.4 (checked using import sys etc.). I have recently installed PyCharm which is the only thing I can think of that has changed. The code works in PyCharm and from IDLE but not from the Command Prompt. Any help would be much appreciated.
From your example , I believe you are running the script using - helloworld.py - this would cause Windows to lookup the default application associated with the extension .py and run it.
I am guessing in your case when you installed PyCharm, it somehow made Python 2.7.7 the default application for .py files (Or it was like that from the start) so when you directly run .py files (even from command prompt) they run using Python 2.7.7 .
You said in your comment that when running python directly from command prompt, you are getting python 3.4 , so the easiest way to fix your issue would be to use that to run your script.
Run it using the command -
python helloworld.py
As a long term solution, you may want to consider changing the default application associated with .py files. You can checkout this link for guide on how to do that
I am in the python command line (using python 2.7), and trying to run a Python script. My operating system is Windows 7. I have set my directory to the folder containing all of my scripts, using:
os.chdir("location").
os.getcwd() returns this location.
When I type:
python myscript.py
I get this error:
File "<stdin>", line 1
python myscript.py
^
SyntaxError: invalid syntax.
What have I done wrong?
The first uncommented line of the script I'm trying to run:
from game import GameStateData
It sounds like you're trying to run your script from within Python. That's not how it works. If you want to run myscript.py, you need to do it from a system command prompt, not from inside the Python interpreter. (For instance, by choosing "Command Prompt" from your start menu. I think it's usually under "Accessories" or something like that.) From there you'll need to change to the directory where your scripts are by using the CD command.
Based on the additional information you have provided it does look like you are issuing the command inside of Python.
EDIT: Maybe part of the confusion comes from the term command line. You are at the command line in both the "Windows command" shell, and also when you are inside the "Python shell".
This is what I get in the command line when inside the Python shell:
D:\Users\blabla \Desktop>python
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python testit.py
File "<stdin>", line 1
python testit.py
^
SyntaxError: invalid syntax
>>>
Or this:
>>> os.chdir("..")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>
My suggestion would be to open a Windows command shell window with the cmd command and then issue your python myscript.py from there.
For more help it would be helpful to see your code, at least the first few lines where the error occurs and some certainty as to where the python command is being issued.
As the other answers indicate, you are probably in the Python shell unintentionally. But if you really do want to run your script from there, try execfile("myscript.py")
on windows shell run echo %PATH%, and check if your .py is under any of the paths.
I'm a begginer in Python and PyDev. I recently made the "helloworld" program in PyDev. My question is: how do I execute it or open it in the interactive Python mode (in Linux terminal) I tried many commands, like ./hello.py, import hello.py, python hello.py, but the only thing I got was SyntaxError: invalid syntax, or some other error.
I also have another question. I have Linux and I opened Eclipse in the terminal (sudo eclipse).
In PyDev, I first went to
File => New => Python Project => HelloWorld (name of project) =>
right click the project => New => PyDev Module => hello (module name).
It is assumed that the name I put in the terminal (running Python) is that of the module, no? Either way, I also tried with the name of the project and nothing. Just to know.
And, when do I use chmod +x? Every time I write it in PyDev, I get an X on the left, which means it's incorrect. Something like this: X chmod +x.
I understand what you're asking now I think. If you want to execute something in a file from the shell, the easiest way is to encapsulate it in a Class.
Try changing your code to the following:
#!/usr/bin/python
class Hello:
def __init__(self):
print "Hello, Interactive Shell World!"
raw_input()
This makes a class called Hello where the constructor function runs the code you have in your current file. Then, start an interactive shell started in the same directory as the hello.py file. Here is a paste from an example session:
>>> from hello import Hello
>>> Hello()
Hello, Interactive Shell World!
<hello.Hello instance at 0xb782686c>
>>>
It prints the message, waits for input, then prints the string representation of the newly created object and returns to the prompt. If you want to avoid the last printout just assign the object to a variable like:
>>> h = Hello()
If you want to keep the ability to execute the file from the command line (rather than the shell) add this code to the bottom of the file:
if __name__ == '__main__':
Hello()
You do "chmod +x" from the terminal. In the directory of the hello.py, run:
chmod +x hello.py
This gives you the ability to run your file like ./hello.py instead of "python hello.py". Now that I think of it, it sounds like you may be confusing the python interactive shell which a unix shell. You can run your file easily using "python hello.py" from a unix shell, but to run code from the python interactive shell, you will want to do something like I did above.
To configure PyDev, make sure you read its getting started manual: http://pydev.org/manual_101_root.html
Now, probably you're having a syntax error because you're using Python 3, where print is no longer a keyword, but a function (so, you have to use print() as a function call), and also have in mind that raw_input() was renamed to input() on Python 3).
To answer your first question to import into interactive mode just use import filename but don't include the .py
C:\Users\CodeThis\Documents\py\search>python
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import aStar
>>> aStar.search((0,0),(5,9))
[(0, 0), (9, 0), (8, 0), (7, 0), (6, 0), (6, 9), (5, 9)]
>>>
something like that anyway