input() causes unexpected EOF SyntaxError - python

I have written a return function for my group project.
I am using python 3.4 and wrote this:
def readrouter(x, y):
conn = sqlite3.connect('server.db')
cur = conn.cursor()
cur.execute("SELECT DISTINCT command FROM router WHERE
function =? or type = ? ORDER BY key ASC",(x, y))
read = cur.fetchall()
return read;
a = input("x:")
b = input("y:")
for result in readrouter(a,b):
print (result[0])
As my major member is using 2.7 and I need to follow his version now.
After I re-input my .py into python 2.7
there is a error:
x:create vlan
Traceback (most recent call last):
File "C:/Users/f0449492/Desktop/2015225/database.py", line 322, in <module>
a = input("x")
File "<string>", line 1
create vlan
^
SyntaxError: unexpected EOF while parsing
Process finished with exit code 1
how to fix this bug?

In Python 2.7, replace input() with raw_input().
The former runs eval() on the input string and expects valid Python code as input. Your input create vlan isn't valid Python and can't be eval'ed. The latter just returns a string with no further processing.

As a follow up - to ensure compatibility with both Python branches you may use six .

Related

Python in ArcGIS

I wrote the following code, which results in an error and I don't know how to fix it to work.
The code is:
# Name: ClipGDBtoNewGDB.py
# Description: Take an input GDB, create a list, iterate through each
feature class, clipping it and writing it to a new GDB.
# Author: tuilbox
# Import system modules
import arcpy, os
from arcpy import env
# Set workspace
env.workspace = arcpy.GetParameterAsText(0)
arcpy.env.overwriteOutput=True
# Set local variables
fclist = arcpy.ListFeatureClasses()
clip_features = arcpy.GetParameterAsText(1)
output_directory=arcpy.GetParameterAsText(2)
xy_tolerance = ""
outgdb=os.path.join(output_directory, arcpy.GetParameterAsText(3))
if not arcpy.Exists(outgdb):
arcpy.CreateFileGDB_management(output_directory,
arcpy.GetParameterAsText(3))
# Execute Clip within for loop
for fc in fclist:
arcpy.Clip_analysis(fc, clip_features, os.path.join(outgdb, fc))
The error is: Traceback (most recent call last):
File "F:/GIS_Joseph/Lab10_Joseph/ClipGDBtoNewGDB.py", line 17, in <module>
arcpy.CreateFileGDB_management(output_directory, arcpy.GetParameterAsText(3))
File "C:\Program Files (x86)\ArcGIS\Desktop10.5\ArcPy\arcpy\management.py", line 18878, in CreateFileGDB
raise e
ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000735: File GDB Location: Value is required
ERROR 000735: File GDB Name: Value is required
Failed to execute (CreateFileGDB).
Any help would be appreciated. Thank you.
With this type of question it would be helpful to let us know what parameters you are passing into your script. Have you passed a valid parameter in position 3? Use arcpy.AddMessage to double check what value you are attempting to pass to arcpy.CreateFileGDB_management.

python 3 NameError

Edit: Thank you for your helpful answers! I downloaded Python 3.7.0 but you are right, my Mac is running Python 2.7. I have homework now :) Figure out how to get it running 3.7. I will come back if I have more questions. Thank you!
Beginner here. I'm getting NameError when executing in Mac with Python Launcher. When testing in Python 3.7.0 Shell it works ok. I've read other answers to NameError questions, but do not understand what I'm doing wrong. Help is appreciated.
Code used
first_name = input ("Hi, what's your first name? ")
print ("Hi," , first_name)
Error received
Traceback (most recent call last):
File "/Users/imperio/Documents/pythonpractice/Name.py", line 1, in <module>
first_name = input ("Hi, what's your first name? ")
File "<string>", line 1, in <module>
NameError: name 'Imperio' is not defined
This is most likely because you are not executing it using Python 3+.
Please check the output of python -V to see which version you are executing your code with.
On mac you may already have both installed, Python 3 is sometimes aliased under python3 file.py
Here's your program converted to valid Python2:
first_name = raw_input ("Hi, what's your first name? ")
print ("Hi, {}".format(first_name))
You're running Python 2. In Python 2, input executes the input. raw_input just returns the string entered.
Here's an example:
>>> x = 1
>>> y = 2
>>> z = 3
>>> print input('variable? ')
variable? x # Note output is the value of the variable
1
>>> print input('variable? ')
variable? w # Variable 'w' doesn't exist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'w' is not defined
>>> print raw_input('variable? ') # Raw input just returns the input.
variable? x
x

Error when importing CSV to postgres with python and psycopg2

I try to COPY a CSV file from a folder to a postgres table using python and psycopg2 and I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
psycopg2.ProgrammingError: must be superuser to COPY to or from a file
HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.
I also tried to run it through the python environment as:
constr = "dbname='db_name' user='user' host='localhost' password='pass'"
conn = psycopg2.connect(constr)
cur = conn.cursor()
sqlstr = "COPY test_2 FROM '/tmp/tmpJopiUG/downloaded_xls.csv' DELIMITER ',' CSV;"
cur.execute(sqlstr)
I still get the above error. I tried \copy command but this works only in psql. What is the alternative in order to be able to execute this through my python script?
EDITED
After having a look in the link provided by #Ilja Everilä I tried this:
cur.copy_from('/tmp/tmpJopiUG/downloaded_xls.csv', 'test_copy')
I get an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument 1 must have both .read() and .readline() methods
How do I give these methods?
Try using cursor.copy_expert():
constr = "dbname='db_name' user='user' host='localhost' password='pass'"
conn = psycopg2.connect(constr)
cur = conn.cursor()
sqlstr = "COPY test_2 FROM STDIN DELIMITER ',' CSV"
with open('/tmp/tmpJopiUG/downloaded_xls.csv') as f:
cur.copy_expert(sqlstr, f)
conn.commit()
You have to open the file in python and pass it to psycopg, which then forwards it to postgres' stdin. Since you're using the CSV argument to COPY, you have to use the expert version in which you pass the COPY statement yourself.
You can also use copy_from. See the code below
with open('/tmp/tmpJopiUG/downloaded_xls.csv') as f:
cur.copy_from(f, table_name,sep=',')
conn.commit()

I'm having troubles with Uber Python API

I'm coding in python, using version 2.6, working with the Uber API, and when I try to import the library uber_rides.auth it throws this error:
Traceback (most recent call last):
File "C:\Inetpub\vhosts\underdevelopment.biz\httpdocs\web\webtemp3\uber\socket.py", line 4, in <module>
from uber_rides.auth import AuthorizationCodeGrant
File "C:\Inetpub\vhosts\underdevelopment.biz\httpdocs\web\webtemp3\uber\uber_rides\auth.py", line 133
query_params = [qp: query_params[qp][0] for qp in query_params]
^
SyntaxError: invalid syntax
The original code of my script is this:
print('Content-Type: text/plain')
print('')
from uber_rides.auth import AuthorizationCodeGrant
def main():
auth_flow = AuthorizationCodeGrant(
'xxxxxx-xxxxxxx',
'xxxxx-xxxxx',
'xxx-xxxxxxxxx',
'',
)
auth_url = auth_flow.get_authorization_url()
if __name__ == "__main__":
main()
It seems the error is from the library but I can't find it yet.
Yes, that's invalid Python syntax. However, it is not clear how you ended up with that file.
Someone or something altered that file. That's not the original source code as distributed by Uber, where that line uses the correct syntax for a dictionary comprehension:
query_params = {qp: query_params[qp][0] for qp in query_params}
Re-install the project, the error is not there upstream.
Note that the above syntax is only available in Python 2.7 and up. You could try to replace it with a dict() call with a generator expression, see Alternative to dict comprehension prior to Python 2.7:
query_params = dict((qp, query_params[qp][0]) for qp in query_params)
Take into account that there may be other issues with the code, upgrading to Python 2.7 is probably the better option.

SQLite3 - Incorrect number of bindings supplied

I am new to SQL, so maybe this is a newbie question. But here is my simple code(also, I am using python):
#classmethod
def next_page(cls):
cls.cur.execute("SELECT * FROM Posts WHERE Id < 10 ORDER BY Date DESC Limit 10")
rows = cls.cur.fetchall()
return rows
When I run this I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "database.py", line 20, in next_page
rows = cls.cur.fetchall()
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied
Any one know what the deal with this is? Any help is appreciated
Turns out(since I was running the code in the REPL) that you have to CTRL+C and enter the REPL again when you modify a file.

Categories

Resources