While reading through the code samples on Youtube API's in python, I encountered that line of code:
print 'Video category: %s' % entry.media.category[[]0].text
(https://developers.google.com/youtube/1.0/developers_guide_python, in Video entry contents section)
What does [[]0] mean? Or is it syntactically incorrect?
It is definitely the mistype.
The correct piece of their api would be print 'Video category: %s' % entry.media.category[0].text:
def PrintEntryDetails(entry):
print 'Video title: %s' % entry.media.title.text
print 'Video published on: %s ' % entry.published.text
print 'Video description: %s' % entry.media.description.text
print 'Video category: %s' % entry.media.category[0].text
print 'Video tags: %s' % entry.media.keywords.text
print 'Video watch page: %s' % entry.media.player.url
print 'Video flash player URL: %s' % entry.GetSwfUrl()
print 'Video duration: %s' % entry.media.duration.seconds
Also, - https://code.google.com/p/gdata-issues/issues/detail?id=3710 have a look at this issue.
The answer from the support there - "Thanks for the report! Looks like there are a few instances of this in our older docs. We'll look into it."
Related
I have a python script that needs to read bytes from a file and publish them in MQTT room. But the file could be recreated during the process (the python script have to be running 24/24).
I tried this code, but when the file is being recreated os.path.isfile always return false.
def mqttToTtyOnMessage(client, userdata, message):
tty = openFile(filename, os.O_WRONLY)
print("%s # %s : Message from %s to %s\n" %
(threadName, time.ctime(time.time()), message.topic, filename))
try:
os.write(tty, message.payload)
except:
print("%s # %s : Unable to write message to file %s\n%s" %
(threadName, time.ctime(time.time()), filename, sys.exc_info()))
while True:
if os.path.isfile(filename):
print("%s # %s : File exist, come back to main loop." % (threadName, time.ctime(time.time())))
subTty = openFile(filename, os.O_WRONLY)
os.write(subTty, message.payload)
break
else:
print("%s # %s : File still not exist, wait few seconds and check again." % (threadName, time.ctime(time.time())))
time.sleep(1)
os.close(tty)
The function openFile looks like this :
def openFile(filename, permission):
try:
fd = os.open(filename, permission)
except:
print("%s # %s : Unable to write message to file %s\n%s" %
(threadName, time.ctime(time.time()), filename, sys.exc_info()))
return (fd)
I hope you have ideas about an error in my code or another way to achieve this.
Thanks
EDIT: Solve this problem by changing the way I checked if the file exist :
def mqttToTtyOnMessage(client, userdata, message):
try:
tty = openFile(filename, os.O_WRONLY)
os.write(tty, message.payload)
print("%s # %s : Message from %s to %s\n" %
(threadName, time.ctime(time.time()), message.topic, filename))
except OSError:
print("%s # %s : Unable to write message to file %s\n%s\n" %
(threadName, time.ctime(time.time()), filename, sys.exc_info()))
while True:
try:
subTty = openFile(filename, os.O_WRONLY)
os.write(subTty, message.payload)
break
except:
print("%s # %s : Can't open file for the moment, try again in 5s.\n%s\n" % ("mqttToTty", time.ctime(time.time()), sys.exc_info()))
time.sleep(5)
os.close(tty)
i'm trying to run this code for my project but its given an error at the try statement i.e "unindent does not match any outer indentation level"
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
DEVELOPER_KEY = "Replaced_my_API_key"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def youtube_search(options):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(
q=options.q,
part="id,snippet",
maxResults=options.max_results
).execute()
videos = []
channels = []
playlists = []
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
videos.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["videoId"]))
elif search_result["id"]["kind"] == "youtube#channel":
channels.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["channelId"]))
elif search_result["id"]["kind"] == "youtube#playlist":
playlists.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["playlistId"]))
print ("Videos:\n", "\n".join(videos), "\n")
print ("Channels:\n", "\n".join(channels), "\n")
print ("Playlists:\n", "\n".join(playlists), "\n")
if __name__ == "__main__":
to_search = "Witcher 3"
argparser.add_argument("--q", help="Search term", default=to_search)
argparser.add_argument("--max-results", help="Max results",
default=25)
args = argparser.parse_args()
**From the following statement the code is giving an error**
i.e "unindent error"
try:
youtube_search(args)
except HttpError, e:
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
This error is common if you are mixing idendation with spaces and tabs. Choose one and stick to it. You can try two things:
Colorize the whitespace in your editor. In vim you can do this with :set list. Find the offending line and correct it.
Give Python the option -tt in the shebang: #!/usr/bin/python -tt. This gives you extra warnings when you are mixing identation in the same file.
I'm trying to execute a python script from Linux but I'm keep getting this error on the except line. Can someone figure this out?
$ python pygeo_ip.py
def search(self):
message = ''
result_count = 0
gip = pygeoip.GeoIP('GeoLIteCity.dat')
ip = self.ip_textbox.text()
try:
ip = socket.gethostbyname(str(ip))
message = "Host: %s Is Currently Available" % (str(ip))
except socket.error, e:
message = "Host: %s Is Currently Unavailable" % (key, val)
result_count += 1
msg_box("SeArCh CoMpLeTe", "%d REsults Were Found For %s"
% (result_count, str(ip))
except Exception, e: <------- Error
msg_box("", str(e))
msg_box("Search Complete", "No Results Were Found For %s" % (str(ip))
return
Error:
File "pygeo_ip.py", line 142
except Exception, e:
^
SyntaxError: invalid syntax
Pretty sure (without having tested anything) your problem is having missed the last close bracket
Line should read:
msg_box("SeArCh CoMpLeTe", "%d REsults Were Found For %s" % (result_count, str(ip)) )
I have a school project that involves programming. I am transferring between batch and python because that is easiest for me.
This is my code written in python:
for i,x in enumerate(result):
if number in x:
print "Start of 1"
cursor.execute(insert1, (number))
cursor.execute(delete, (number))
f.close()
os.system("extracommands.bat 1")
print "Found Number"
else:
print "Start of 2"
cursor.execute(insert1, (number))
cursor.execute(insert2, (number))
cursor.execute(delete, (number))
f.close()
os.system("emailfine.py 1")
print "Finished 2"
My problem is that I can't find a string in a tuple. What happens is that when there is a result, it runs perfectly. But when there isn't a result, nothing happens.
How can I overcome this?
Thank you in advance.
Edit:
I was probably not specific enough when asking my question.
The result variable is in fact a MySQL execution result using the fetchall() command. The whole code of my program is:
import MySQLdb
import sys
import os
print "=========================="
print "Start Registered_Or_Not.py"
print "=========================="
os.chdir("C:/DisabledParkingSpacesImages/textfiles")
f = open("numberplate.txt", "r")
number = f.read()
print number
try:
db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = 'jordan',
db = 'disabledparking'
)
except Exception as e:
sys.exit("Can't access the database")
print "MySQL Connection OK"
cursor = db.cursor()
cursor.execute("SELECT registration FROM registered WHERE EXISTS (SELECT 1 FROM limbo WHERE limbo.registration = registered.registration)")
result = cursor.fetchall()
insert1 = "INSERT INTO log (registration, time, date) VALUES(%s, CURRENT_TIME, CURRENT_DATE);"
insert2 = "INSERT INTO not_registered (registration, time, date) VALUES(%s, CURRENT_TIME, CURRENT_DATE);"
delete = "DELETE FROM limbo WHERE registration=%s;"
print "-------------"
print "Result:"
print result
print "-------------"
TrueFalse = False
for i,x in enumerate(result):
if number in x:
print "Start of 1"
cursor.execute(insert1, (number))
cursor.execute(delete, (number))
f.close()
os.system("extracommands.bat 1")
print "Found Number"
TrueFalse = True
elif TrueFalse == False:
print "Start of 2"
cursor.execute(insert1, (number))
cursor.execute(insert2, (number))
cursor.execute(delete, (number))
f.close()
os.system("emailfine.py 1")
print "Finished 2"
db.commit()
OK, So I answered my own question.
Here is the problematic code:
for i,x in enumerate(result):
if number in x:
print "Start of 1"
cursor.execute(insert1, (number))
cursor.execute(delete, (number))
f.close()
os.system("extracommands.bat 1")
print "Found Number"
else:
print "Start of 2"
cursor.execute(insert1, (number))
cursor.execute(insert2, (number))
cursor.execute(delete, (number))
f.close()
os.system("emailfine.py 1")
print "Finished 2"
And here is the non problematic code:
for i,x in enumerate(result):
if number in x:
print "Start of 1"
cursor.execute(insert1, (number))
cursor.execute(delete, (number))
f.close()
os.system("extracommands.bat 1")
print "Found Number"
TrueFalse = True
if TrueFalse == False:
print "Start of 2"
cursor.execute(insert1, (number))
cursor.execute(insert2, (number))
cursor.execute(delete, (number))
f.close()
os.system("emailfine.py 1")
print "Finished 2"
I'm trying to make a bitbucket request from python to return a list of my repos. It's responding, but the formatting is including "\n" characters, I assume my encoding is wrong, but don't know how to fix it.
How do I encode my response to be formatted JSON.
theurl = 'https://api.bitbucket.org/1.0/user/repositories/';
username = 'xxxxx';
password = 'xxxxx';
passman = urllib2.HTTPPasswordMgrWithDefaultRealm();
passman.add_password(None, theurl, username, password);
authhandler = urllib2.HTTPBasicAuthHandler(passman);
opener = urllib2.build_opener(authhandler);
urllib2.install_opener(opener);
pagehandle = urllib2.urlopen(theurl);
output = pagehandle.decode('utf-8');
responseH = output.read();
Why don't you try using python-bitbucket? Example below
from api import API
import datetime
api = API("username", "**password**")
repos = api.get_repositories()
for repo in repos:
print "Name: %s" % repo.name
print "Owner: %s" % repo.owner
print "Website: %s" % repo.website
print "Description: %s" % repo.description
print "Created on: %s" % datetime.datetime.strftime(repo.created_on, "%c")
print "Language: %s" % repo.language
print "SCM: %s" % repo.scm
for issue in repo.get_issues():
# Yes, this works too!
print "Issue title: %s" % issue.title
print "Issue priority: %s" % issue.priority
print "Issue content:\n%s\n\n" % issue.content
for change in repo.get_changesets(limit=5):
print "Revision/Node: %d:%s" % (change.revision, change.node)
# Since change.timestamp is a datetime object, we can use formatting on it.
print "Timestamp: %s" % datetime.datetime.strftime(change.timestamp, "%c")
print "Commit message:\n%s" % change.message
print "Affected files: %s" % len(change.files)
for f in change.files:
print f.filename
print "\n"