Error in print function [duplicate] - python

This question already has answers here:
Python print statement “Syntax Error: invalid syntax” [duplicate]
(2 answers)
Closed 8 years ago.
I am new to Python and I am trying to run the following lines in Python 3.4. The file is downloaded from Yelp.com and is ready-to-use:
url_params = url_params or {}
url = 'http://{0}{1}?'.format(host, path)
consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET)
oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params)
oauth_request.update(
{
'oauth_nonce': oauth2.generate_nonce(),
'oauth_timestamp': oauth2.generate_timestamp(),
'oauth_token': TOKEN,
'oauth_consumer_key': CONSUMER_KEY
}
)
token = oauth2.Token(TOKEN, TOKEN_SECRET)
oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token)
signed_url = oauth_request.to_url()
print 'Querying {0} ...'.format(url)
In the last line:
print 'Querying {0} ...'.format(url) I get an error message: SyntaxError: invalid syntax

In Python 3 and up the argument to print has to be inside parenthesis:
print('Querying {0} ...'.format(url))

In Python 3x you have to put paranthesis in print function.
print ('Querying {0} ...'.format(url))
For example you can't do this;
print "hello"
You have to write that like;
print ("hello")

Related

Python -IndentationError: unexpected unindent (Making Reddit Bot) [duplicate]

This question already has answers here:
What should I do with "Unexpected indent" in Python?
(18 answers)
Closed 2 years ago.
IndentationError: unexpected unindent WHY? Here's my code:
from praw.models import MoreComments
import praw
import giris
import time
import os
def bot_login():
print("Loggin in...")
r = praw.Reddit(username = giris.username,
password = giris.password,
client_id = giris.client_id,
client_secret = giris.client_secret,
user_agent = "karton_bardak_bot")
print("Logged in!")
return r
info="""
\n
\n
\n
^(ben bot) \n
\n
^(bruh)
"""
subreddit=r.subreddit("shithikayeler")
def run_bot(r, comments_replied_to):
print("Obtaining 25 comments...")
for submission in subreddit.new():
toReply=True
for top_level_comment in submission.comments:
if isinstance(top_level_comment, MoreComments):
continue
if not submission.is_self:
toReply=False
if top_level_comment.author=="karton_bardak_bot" or submission.selftext=='':
toReply=False
print("PASSED "+ submission.url)
log.write("PASSED "+ submission.url+"\n")
if toReply:
try:
new=reply(submission.selftext, info)
submission.reply(new)
except Exception as e:
log.write("ERROR: " + str(e) + " on submission " + submission.url)
print("REPLIED "+ submission.url)
log.write("REPLIED "+submission.url+"\n")
try:
time.sleep(60)
r = bot_login
while True:
run_bot(r)
It says:
File "bot.py", line 57
r = bot_login
^
IndentationError: unexpected unindent
Why? I have checked a thousands times and I can't find the problem. Pls help.
Because you start a
try:
block with out giving it the needed
except:
part... exactly here:
try:
time.sleep(60)
r = bot_login
so it complains about r = bot_login being maliciously wrong indented.
The code either expects you to stay inside the try: indentation to add more code or ex-dent once and add the except ... : part of the statement followed by another indent for it`s code.
See python.org tutorial about handling exceptions

Flask:The view function did not return a valid response tuple [duplicate]

This question already has answers here:
Flask view raises TypeError: 'bool' object is not callable
(1 answer)
Return JSON response from Flask view
(15 answers)
Closed 4 years ago.
The view function did not return a valid response tuple. To tuple must have the form (body, status, headers), (body, status), or (body, headers).
This was the error I got, when I was executing my code.
def success(name, diff, cat):
url = "https://opentdb.com/api.php?amount=10&category="+cat+"&difficulty="+diff
response = requests.get(url)
fp = response.content
obj = json.loads(fp)
ans_li = ['abcd']
for x in obj["results"]:
question = x['question']
answer = x['correct_answer']
ans_li[0] = answer
incorrect_ans = x['incorrect_answers']
options = ans_li+incorrect_ans
random.shuffle(options)
makeitastring = ' '.join(map(str, options))
makeitastring+=makeitastring
app.logger.info(options)
return tuple(options)
Also I am getting just first value in the loop, whereas I want it to traverse the entire loop and print out all options.

get() takes exactly 1 argument (3 given) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
#!/usr/bin/env python
import requests, json
userinput = raw_input('Enter a keyword: ')
getparams = {'order':'desc', 'sort':'votes', 'intitle':userinput, 'site':'stackoverflow', 'filter': '!5-HwXhXgkSnzI0yfp0WqsC_-6BehEi(fRTZ7eg'}
r = requests.get('https://api.stackexchange.com/2.2/search', params=getparams)
result = json.loads(r.text)
if result['has_more'] == False:
print 'Error given.'
else:
for looping in result['items']:
print ''
print ''
print 'Title:', looping['title']
#print 'Question:', looping['body']
print 'Link:', looping['link']
if looping['is_answered'] == True:
try:
print 'Answer ID#:', looping['accepted_answer_id']
newparams = {'order':'desc', 'sort':'votes', 'site':'stackoverflow', 'filter': '!4(Yrwr)RRK6oy2JSD'}
newr = requests.get('https://api.stackexchange.com/2.2/answers/', looping['accepted_answer_id'], params=newparams)
newresult = json.loads(newr.text)
print newresult['items'][0]['body']
except KeyError: print 'No answer ID found.'
print ''
print ''
I am trying to make a request such as "https://api.stackexchange.com/2.2/answers/12345 (User inputs 12345)" but I don't know how to do that. And if I include a string it returns error. Help, please?
I am getting this error:
Enter a keyword: php
Title: How can I prevent SQL-injection in PHP?
Link: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
Answer ID#: 60496
Traceback (most recent call last):
File "./warrior.py", line 25, in <module>
newr = requests.get('https://api.stackexchange.com/2.2/answers/', looping['accepted_answer_id'], params=newparams)
TypeError: get() takes exactly 1 argument (3 given)
update the request line as
newr = requests.get('https://api.stackexchange.com/2.2/answers/'+str(looping['accepted_answer_id']), params=newparams)
you need to concatenate the looping['accepeted answer']

Multiple Term search by following multiple users using Streaming API

I am trying to Retrieve multiple keyword term tweets by following specific group of users. Using the code below:
I have posted one more code before that regarding issues for value error:
I figure it out somehow but again I am stuck because of this traceback
import tweepy
from tweepy.error import TweepError
consumer_key=('ABC'),
consumer_secret=('ABC'),
access_key=('ABC'),
access_secret=('ABC')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api=tweepy.API(auth)
class CustomStreamListener(tweepy.StreamListener):
def on_status(self, status):
try:
print "%s\t%s\t%s\t%s" % (status.text,
status.author.screen_name,
status.created_at,
status.source,)
except Exception, e:
print error
#def filter(self, follow=None, track=None, async=False, locations=None):
#self.parameters = {}
#self.headers['Content-type'] = "application/x-www-form-urlencoded"
#if self.running:
#raise TweepError('Stream object already connected!')
#self.url = '/%i/statuses/filter.json?delimited=length' % STREAM_VERSION
def filter(self, follow=None, track=None, async=False, locations=None):
self.parameters = {}
self.headers['Content-type'] = "application/x-www-form-urlencoded"
if self.running:
raise TweepError('Stream object already connected!')
self.url = '/%i/statuses/filter.json?delimited=length' % STREAM_VERSION
if obey:
self.parameters['follow'] = ' '.join(map(str, obey))
if track:
self.parameters['track'] = ' '.join(map(str, track))
if locations and len(locations) > 0:
assert len(locations) % 4 == 0
self.parameters['locations'] = ' '.join('%.2f' % l for l in locations)
self.body = urllib.urlencode(self.parameters)
self.parameters['delimited'] = 'length'
self._start(async)
def on_error(self, status_code):
return True
streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=60)
list_users = ['17006157','59145948','157009365','16686144','68044757','33338729']#Some ids
list_terms = ['narendra modi','robotics']#Some terms
streaming_api.filter(follow=[list_users])
streaming_api.filter(track=[list_terms])
I am getting a traceback:
Traceback (most recent call last):
File "C:\Python27\nytimes\26052014\Multiple term search with multiple addreses.py", line 49, in <module>
streaming_api.filter(follow=[list_users])
File "build\bdist.win32\egg\tweepy\streaming.py", line 296, in filter
encoded_follow = [s.encode(encoding) for s in follow]
AttributeError: 'list' object has no attribute 'encode'
Please help me resolving the issue.
You define list_users here
list_users = ['17006157','59145948','157009365','16686144','68044757','33338729']
and then you pass it to streaming_api.filter like this
streaming_api.filter(follow=[list_users])
When the streaming_api.filter function is iterating over the value you pass as follow, it gives the error
AttributeError: 'list' object has no attribute 'encode'
The reason for this is as follows
You call streaming_api.filter like this
streaming_api.filter(follow=[list_users])
Here
streaming_api.filter(follow=[list_users])
you are trying to pass your list as value for follow, however because you put list_users in enclosing [] you are creating a list in a list. Then streaming_api.filter iterates over follow, calling .encode on each entry as we see here
[s.encode(encoding) for s in follow]
But the entry s is a list while it should be a string.
That is because you accidentally created a list in a list like you can see above.
The solution is simple. Change
streaming_api.filter(follow=[list_users])
to
streaming_api.filter(follow=list_users)
To pass a list to a function, you can just specify the name. No need to enclose it in []
Same applies to the last line. Change
streaming_api.filter(track=[list_terms])
to
streaming_api.filter(track=list_terms)

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