Syntax error in for line in python - python

I am running a python script. I am getting an unexplained syntax error in for line.
This is the code:
today = datetime.date.today()
url="http://www.99acres.com/property-in-velachery-chennai-south-ffid?"
print "INSERT INTO Property (URL,Rooms, Place, Phonenumber1,Phonenumber2,Phonenumber3,Typeofperson, Name)"
print "VALUES ("
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
properties = soup.findAll(('a', {'title':re.compile('Bedroom')}),('i',{'class':'pdate'})
for eachproperty in properties:
print today,","+ "http:/" + eachproperty['href'] ",", eachproperty.string"," ,.join(re.findall("'([a-zA-Z0-9,\s]*)'", eachproperty['onclick']))
print ")"
Error is
$ python properties.py
File "properties.py", line 15
for eachproperty in properties:
^
SyntaxError: invalid syntax
Update
Is the following line correct ?
properties = soup.findAll(('a', {'title':re.compile('Bedroom')}),('i',{'class':'pdate'}))

The preceding line has an incorrect count of opening ( parenthesis compared to the number of closing parens:
properties = soup.findAll(('a', {'title':re.compile('Bedroom')}),('i',{'class':'pdate'})
# --^^ ---^ ---^-^-^ -----^
Add one more closing ):
properties = soup.findAll(('a', {'title':re.compile('Bedroom')}),('i',{'class':'pdate'}))

Related

Unexpected indent error while i break my url to short length as per PEP8 guideline

I tried to make url of short length but its giving unexpected indent.i provided the piece of code on which its giving error
trackback:
Traceback (most recent call last):
File "C:\Users\HOME\Desktop\movie trailer\entertainment.py", line 1, in
import media
File "C:\Users\HOME\Desktop\movie trailer\media.py", line 85
"/w185"+str(detail_new[4])"
^
IndentationError: unexpected indent
self.poster_image_url = "http://image.tmdb.org/t/p"
"/w185"+str(detail_new[4])"
self.trailer_youtube_url =
"https://www.youtube.com/watch?"
"v="+str(self.get_trailer_link(movie_name))"
You should use "\" to indicate to Python that the line does not terminate:
my_variable = "beginning of the string" \
"end of the string"
For your second case:
my_variable = \
"beginning of the string" \
"end of the string"
You can also use parentheses for the same purpose:
my_variable = (
"beginning of the string"
"end of the string"
)
For your specific case:
self.poster_image_url = (
'http://image.tmdb.org/t/p'
'/w185' + str(detail_new[4])
)
self.trailer_youtube_url = (
'https://www.youtube.com/watch?'
'v=' + str(self.get_trailer_link(movie_name))
)
self.poster_image_url = "http://image.tmdb.org/t/p \
/w185+str({0})])".format(detail_new[4])
self.trailer_youtube_url = "https://www.youtube.com/watch?" \
"v=" + "str({0})".format(self.get_trailer_link(movie_name))

TypeError: unsupported format string passed to bytes.__format__

Hi I'm trying to print an sqlite file to a readable format. I'm using dionea honeynet's python script. I encounter this error every time I run the script:
File "./readlogsqltree.py", line 268, in print_logins
login['login_password']))
TypeError: unsupported format string passed to bytes.__format__
The login['login_password'] is a variable taken from a select statement. Here is the function that is being called:
def print_logins(cursor, connection, indent):
r = cursor.execute("""
SELECT
login_username,
login_password
FROM
logins
WHERE connection = ?""", (connection, ))
logins = resolve_result(r)
for login in logins:
print("{:s} login - user:'{:s}' password:'{:s}'".format(
' ' * indent,
login['login_username'],
login['login_password']))
Resolve result function:
def resolve_result(resultcursor):
names = [resultcursor.description[x][0] for x in range(len(resultcursor.description))]
resolvedresult = [ dict(zip(names, i)) for i in resultcursor]
return resolvedresult
Cursor:
def print_db(opts, args):
dbpath = 'logsql.sqlite'
if len(args) >= 1:
dbpath = args[0]
print("using database located at {0}".format(dbpath))
dbh = sqlite3.connect(dbpath)
cursor = dbh.cursor()
I was encountering this error when converting some python2 script to python3:
File "/home/user/Documents/projects/tf-booking/tensorflow-object-detection-example/object_detection_app/app.py", line 152, in encode_image
base64.b64encode(image_buffer.getvalue()))
TypeError: unsupported format string passed to bytes.__format__
Solution was to use base64.b64encode(image_buffer.getvalue()).decode() instead of base64.b64encode(image_buffer.getvalue()) as in this post.
For Python 3, decode the string using decode('utf-8') before calling format()

I am getting this error "TypeError: str() takes at most 1 argument (2 given)" at "client_response" variable

EDIT to format:
This is the original code
from __future__ import print_function
import socket
import sys
def socket_accept():
conn, address = s.accept()
print("Connection has been established | " + "IP " + address[0] + "| Port " + str(address[1]))
send_commands(conn)
conn.close()
def send_commands(conn):
while True:
cmd = raw_input()
if cmd == 'quit':
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024), "utf-8")
print(client_response, end ="")
def main():
socket_accept()
main()
I am getting this error “TypeError: str() takes at most 1 argument (2 given)” at “client_response” variable
You have your error here:
client_response = str(conn.recv(1024), "utf-8")
Just change it to:
client_response = str(conn.recv(1024)).encode("utf-8")
On the second to last line you're passing two arguments to the str function, although the str function only takes a single argument in Python 2. It does in fact take up to three arguments in python 3
https://docs.python.org/2.7/library/functions.html?highlight=str#str
https://docs.python.org/3.6/library/functions.html?highlight=str#str
So you're either trying to inadvertaetly run python 3 code in a python 2 interpreter or you're looking at the wrong language documentation.
So either use #franciscosolimas's answer, if you're using python 2, or make sure you're using python 3, if the latter you might also want to add a keyword argument just to make sure you know what's happening in the future
client_response = str(conn.recv(1024), encoding="utf-8")
3 arguments, 5 given
I got a similar error, may not be the same here (as the op) but, it was simple enough fix and wanted to share, since I ended up here from my searches on the error.
Traceback (most recent call last):
File "queries.py", line 50, in <module>
"WHERE ao.type='u';")
TypeError: str() takes at most 3 arguments (5 given)`
What fixed it for me in python3 was converting my ,'s to +
Error:
str("SELECT s.name + '.' + ao.name, s.name"
"FROM sys.all_objects ao",
"INNER JOIN sys.schemas s",
"ON s.schema_id = ao.schema_id",
"WHERE ao.type='u';"))
Fixed:
str("SELECT s.name + '.' + ao.name, s.name " +
"FROM sys.all_objects ao " +
"INNER JOIN sys.schemas s " +
"ON s.schema_id = ao.schema_id " +
"WHERE ao.type='u';")
I had to add my own spaces so the passed query would work.
As the commas were doing that in python...
Thoughts & my educated guess:
looks like in my case it got caught up trying to evaluate in bash/python a litteral u'
To my knowledge this break could be in bash because there is no command called u and/or in python u' is you trying to unicode an incomplete string. Either way it broke and wanted to share my fix.
Cheers!
~JayRizzo

Python pyparsing issue

I am very new to python and using pyparsing but getting some exception with following code
while site_contents.find('---', line_end) != line_end + 2:
cut_start = site_contents.find(" ", site_contents.find("\r\n", start))
cut_end = site_contents.find(" ", cut_start+1)
line_end = site_contents.find("\r\n", cut_end)
name = site_contents[cut_start:cut_end].strip()
float_num = Word(nums + '.').setParseAction(lambda t:float(t[0]))
nonempty_line = Literal(name) + Word(nums+',') + float_num + Suppress(Literal('-')) + float_num * 2
empty_line = Literal(name) + Literal('-')
line = nonempty_line | empty_line
parsed = line.parseString(site_contents[cut_start:line_end])
start = line_end
Exception
Traceback (most recent call last):
File "D:\Ecllipse_Python\HellloWorld\src\HelloPython.py", line 108, in <module>
parsed = line.parseString(site_contents[cut_start:line_end]) # parse line of data following cut name
File "C:\Users\arbatra\AppData\Local\Continuum\Anaconda\lib\site-packages\pyparsing.py", line 1041, in parseString
raise exc
pyparsing.ParseException: Expected W:(0123...) (at char 38), (line:1, col:39)
how to resolve this issue?
You'll get a little better exception message if you give names to your expressions, using setName. From the "Expected W:(0123...)" part of the exception message, it looks like the parser is not finding a numeric value where it is expected. But the default name is not showing us enough to know which type of numeric field is expected. Modify your parser to add setName as shown below, and also change the defintion of nonempty_line:
float_num = Word(nums + '.').setParseAction(lambda t:float(t[0])).setName("float_num")
integer_with_commas = Word(nums + ',').setName("int_with_commas")
nonempty_line = Literal(name) + integer_with_commas + float_num + Suppress(Literal('-')) + float_num * 2
I would also preface the call to parseString with:
print site_contents[cut_start:line_end]
at least while you are debugging. Then you can compare the string being parsed with the error message, including the column number where the parse error is occurring, as given in your posted example as "(at char 38), (line:1, col:39)". "char xx" starts with the first character as "char 0"; "col:xx" starts with the first column as "col:1".
These code changes might help you pinpoint your problem:
print "12345678901234567890123456789012345678901234567890"
print site_contents[cut_start:line_end]
try:
parsed = line.parseString(site_contents[cut_start:line_end])
except ParseException as pe:
print pe.loc*' ' + '^'
print pe
Be sure to run this in a window that uses a monospaced font (so that all the character columns line up, and all characters are the same width as each other).
Once you've done this, you may have enough information to fix the problem yourself, or you'll have some better output to edit into your original question so we can help you better.

Formatting a variable as a string

I am trying to create a Python program that will query a URL and produce a JSON file. I need to pass an argument in the end of the URL which comes from the SQL query.
I have imported the requests library.
I get an error message 'TypeError: float argument required, not str' when I am trying to pass argument in the URL.
There is only one column of result produced from the query:
id
2
3
4
Below is what I came up with:
import MySQLdb
import requests
con=MySQLdb.connect(host="localhost",user="test", passwd="test", db ="mfg")
cur = con.cursor()
select=("select id from tblMfg")
cur.execute(select)
result=cur.fetchall()
for i in result:
col =i[0]
col1=str(col)
url = 'http://appl.xyz.net:8080/app/content/pq/doQuery?solution=nd&path=&file=Test.nd&dataAccessId=1&paramid=%d' % col1
user = 'abc'
password ='testgo'
data = requests.get(url, auth=(user, password))
json_data=data.json()
print json_data
Leave creating parameters to the requests framework instead:
params = {'solution': 'nd', 'path': '', 'file': 'Test.nd', 'dataAccessId': '1',
'paramid': str(col[0])}
url = 'http://appl.xyz.net:8080/app/content/pq/doQuery'
user = 'abc'
password ='testgo'
data = requests.get(url, auth=(user, password), params=params)
The error message 'TypeError: float argument required, not str' also occurs when you try to format a string containing an (accidental) naked percent sign.
Example:
>>> print "fail 100% for serverid|%s| " % ("a")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: float argument required, not str
>>>
The "f" after the "100% " is interpreted as asking for a floating point argument, whereas it was simply my smudgefingers leaving off the second percent sign.
>>> print "fail 100%% for serverid|%s| " % ("a")
fail 100% for serverid|a|
>>>
works fine. If the word following the "100% " begins with d or o or s, you get slightly different error messages.
I was unlucky enough to have this happen several call layers inside a 2-nested try-except, so the error showed up a mile away from the line that caused it.
print ("float_value : %f , digit_value : %d , string_value : %s" % (3.4, 5, 'somestring'))
float_value : 3.400000 , digit_value : 5 , string_value : somestring

Categories

Resources