I have found this code sample to make a query in ebay from here and also downloaded ebay-sdk for Python. How can I install the sdk and integrate this code with it?
from ebaysdk import finding, nodeText
f = finding()
f.execute('findItemsAdvanced', {'keywords': 'shoes'})
dom = f.response_dom()
mydict = f.response_dict()
myobj = f.response_obj()
print myobj.itemSearchURL
# process the response via DOM
items = dom.getElementsByTagName('item')
for item in items:
print nodeText(item.getElementsByTagName('title')[0])
It is quite a simple process
1) Go to http://developer.ebay.com/, register over there, and get
the app id key.
2) You can simply do a 'pip install ebaysdk' to
install the ebaysdk
3) Copy this file in the same directory
https://github.com/timotheus/ebaysdk-python/blob/master/ebay.yaml In
this file replace appid with what you generated in step 1
4) Execute the example, this time it will work :)
Related
This question already has answers here:
How to make this script loop every hour
(4 answers)
Closed 2 years ago.
I am making a script wich post every hour on twitter every case of coronavirus. I have it finish but idk how to make that it posts every hour. any idea? (if you could post the following script with the solution in would be perfect)
import sys
CONSUMER_KEY = 'XXXX'
CONSUMER_SECRET = 'XXXX'
ACCESS_TOKEN = 'XXXX'
ACCESS_TOKEN_SECRET = 'XXXX'
import tweepy
import requests
from lxml import html
def create_tweet():
response = requests.get('https://www.worldometers.info/coronavirus/')
doc = html.fromstring(response.content)
total, deaths, recovered = doc.xpath('//div[#class="maincounter-number"]/span/text()')
tweet = f'''Coronavirus Latest Updates
Total cases: {total}
Recovered: {recovered}
Deaths: {deaths}
Source: https://www.worldometers.info/coronavirus/
#coronavirus #covid19 #coronavirusnews #coronavirusupdates #COVID19
'''
return tweet
if __name__ == '__main__':
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
# Create API object
api = tweepy.API(auth)
try:
api.verify_credentials()
print('Authentication Successful')
except:
print('Error while authenticating API')
sys.exit(5)
tweet = create_tweet()
api.update_status(tweet)
print('Tweet successful')
Best way is to Schedule Python Script using Windows Scheduler on Windows & Cron Jobs on Linux. Following are the steps for Scheduling your python script on windows.
Prepare the Python Script
Save the Python Script
Create Batch File to Run the Python Script with extension .Bat
Content should be as follows
"Path where your Python exe is stored\python.exe" "Path where your Python script
is stored\script name.py"
pause
This batch file will run the Python script when double-clicking on it
In the final step below, you’ll see how to schedule that batch file
to execute the Python Script using the Windows Scheduler.
First, open the Control Panel and then click on the Administrative
Tools: Next, double-click on the Task Scheduler, and then choose the
option to ‘Create Basic Task…’
Type a name for your task (you can also type a description if needed), and then press Next.
Next, I chose to start the task ‘Daily’ since we wish to run the Python script daily at 6am:
The action will then recur everyday at 6am, staring from start date. You can adjust those timing parameters to suit your needs.
Select, Start a program, and then press Next:
Next, use the Browse button to find the batch file that runs the Python script.
click on Finish,
We go to the ‘Triggers’ tab and select the ‘Edit’ option:
An ‘Edit Trigger’ screen will appear. To set the script to run hourly, we select the ‘Repeat task…’ option and enable it. We select the ‘1 hour’ option, indicating that we wish for the task to execute on an hourly basis, and select the duration as indefinite under the duration option.
We then press the ‘OK’ button and exit the popup. Our batch script is enabled to run hourly at the :00 mark!
you should be good to go.
Above shared information is enough to do your job, But for more information, Feel free to use the link as below: https://datatofish.com/python-script-windows-scheduler/ and https://techrando.com/2019/06/22/how-to-execute-a-task-hourly-in-task-scheduler/
I am trying to make a weather search tool using sys.argv and just wanted some help. I have the current code
The problem is when I search using the command line I need to type in the country. Is there a way to do it searching only the city?:
#! /usr/bin/env python3
import webbrowser
import sys
import pyperclip
import re
if len(sys.argv) > 1:
#Get address from command line.
address = ' '.join(sys.argv[1:])
else:
address = pyperclip.paste()
webbrowser.open('https://www.timeanddate.com/weather/' + address)
command line:
./weather.py spain/madrid
./weather.py uk/london
As was mentioned, there are probably a number of packages that will do the trick, and likely none of them will work for certain city names. However, geonamescache is very easy to use and will do the trick for unique names. Here is an example (will return "Canada" for "Toronto" as input)
pip install geonamescache
import geonamescache as gnc
gc = gnc.GeonamesCache()
query = 'Toronto'
citykey = list(gc.get_cities_by_name(query)[0])[0]
ccode = gc.get_cities_by_name(query)[0][citykey]['countrycode']
countries = gc.get_countries()
country_name = countries[ccode]['name']
print(country_name)
1-) Register geonames to use API
Create a new user account https://www.geonames.org/login
Activate your account from mail
On the redirected page after clicking activation link, activate web services
2-) Install geocoder
pip install geocoder
3-) Use API
import geocoder
g = geocoder.geonames('madrid', key='YOURUSERNAMEHERE')
...
webbrowser.open('https://www.timeanddate.com/weather/' + g.country + address)
As #Kalma mentioned, g.country returns 'United Kingdom' instead of 'UK'. You might need to map these values to the ones that timeanddate.com accepts.
I am trying to get a list of workset name and id's from the active document using Revit API inside of Python node in Dynamo. I am trying to access workset table but this code returns nothing:
doc = __doc__
workset = ActiveWorkset(doc)
active_id = workset.ActiveWorksetId()
OUT = active_id
For now I was just trying to see if i can get active workset first but even that doesnt work.
I haven't tried this in Dynamo, but my trusty RevitPythonShell thinks this should work:
worksetTable = doc.GetWorksetTable()
activeId = worksetTable.GetActiveWorksetId()
workset = worksetTable.GetWorkset(activeId)
this is based on the example from the Revit 2014 API document in the SDK...
The output:
>>> workset
<Autodesk.Revit.DB.Workset object at 0x000000000000002E [Autodesk.Revit.DB.Workset]>
Based on your example, you probably want to do this at the end:
OUT = activeId
I am writing a Rhythmbox plugin to iterate over all podcast files currently known to Rhythmbox (whether downloaded or not) and to do something with them.
After some research and testing in the Rhythmbox's Python Shell, I succeeded to get a list of all objects. However, when I coded it into a plugin, I get an error:
(rhythmbox:7500): GLib-GObject-WARNING **: invalid cast from `RhythmDBTree' to `RhythmDBEntryType'
and the entries list is empty:
def run(self, action, shell):
db = shell.get_property('db')
entry_type = db.entry_type_get_by_name('podcast-post')
print entry_type
entries = []
db.entry_foreach_by_type(entry_type, entries.append)
print entries
However, the print entry_type returns: <rhythmdb.EntryType object at 0xa7ea34c (RhythmDBEntryType at 0xa106988)>, so the db object is apparently valid.
What am I doing wrong?
First try to reinstall rhythmbox.
See what this outputs, it runs fine on my machine, post what this outputs on your machine
from __future__ import print_function
def plugin_create(database):
print(database)
db.entry_foreach_by_type(db.entry_type_get_by_name('podcast-post'), print)
I tried the following:
def run(self, action, shell):
db = shell.get_property('db')
entry_type = db.entry_type_get_by_name('podcast-post')
print entry_type
entries = []
db.entry_foreach(entries.append)
print entries
for entry in entries:
if entry.get_type() == entry_type:
# process entry...
and it works correctly. Well, not the most beautiful solution, but it is OK for my needs.
I'm brand new at Python and I'm trying to write an extension to an app that imports GA information and parses it into MySQL. There is a shamfully sparse amount of infomation on the topic. The Google Docs only seem to have examples in JS and Java...
...I have gotten to the point where my user can authenticate into GA using SubAuth. That code is here:
import gdata.service
import gdata.analytics
from django import http
from django import shortcuts
from django.shortcuts import render_to_response
def authorize(request):
next = 'http://localhost:8000/authconfirm'
scope = 'https://www.google.com/analytics/feeds'
secure = False # set secure=True to request secure AuthSub tokens
session = False
auth_sub_url = gdata.service.GenerateAuthSubRequestUrl(next, scope, secure=secure, session=session)
return http.HttpResponseRedirect(auth_sub_url)
So, step next is getting at the data. I have found this library: (beware, UI is offensive) http://gdata-python-client.googlecode.com/svn/trunk/pydocs/gdata.analytics.html
However, I have found it difficult to navigate. It seems like I should be gdata.analytics.AnalyticsDataEntry.getDataEntry(), but I'm not sure what it is asking me to pass it.
I would love a push in the right direction. I feel I've exhausted google looking for a working example.
Thank you!!
EDIT: I have gotten farther, but my problem still isn't solved. The below method returns data (I believe).... the error I get is: "'str' object has no attribute '_BecomeChildElement'" I believe I am returning a feed? However, I don't know how to drill into it. Is there a way for me to inspect this object?
def auth_confirm(request):
gdata_service = gdata.service.GDataService('iSample_acctSample_v1.0')
feedUri='https://www.google.com/analytics/feeds/accounts/default?max-results=50'
# request feed
feed = gdata.analytics.AnalyticsDataFeed(feedUri)
print str(feed)
Maybe this post can help out. Seems like there are not Analytics specific bindings yet, so you are working with the generic gdata.
I've been using GA for a little over a year now and since about April 2009, i have used python bindings supplied in a package called python-googleanalytics by Clint Ecker et al. So far, it works quite well.
Here's where to get it: http://github.com/clintecker/python-googleanalytics.
Install it the usual way.
To use it: First, so that you don't have to manually pass in your login credentials each time you access the API, put them in a config file like so:
[Credentials]
google_account_email = youraccount#gmail.com
google_account_password = yourpassword
Name this file '.pythongoogleanalytics' and put it in your home directory.
And from an interactive prompt type:
from googleanalytics import Connection
import datetime
connection = Connection() # pass in id & pw as strings **if** not in config file
account = connection.get_account(<*your GA profile ID goes here*>)
start_date = datetime.date(2009, 12, 01)
end_data = datetime.date(2009, 12, 13)
# account object does the work, specify what data you want w/
# 'metrics' & 'dimensions'; see 'USAGE.md' file for examples
account.get_data(start_date=start_date, end_date=end_date, metrics=['visits'])
The 'get_account' method will return a python list (in above instance, bound to the variable 'account'), which contains your data.
You need 3 files within the app. client_secrets.json, analytics.dat and google_auth.py.
Create a module Query.py within the app:
class Query(object):
def __init__(self, startdate, enddate, filter, metrics):
self.startdate = startdate.strftime('%Y-%m-%d')
self.enddate = enddate.strftime('%Y-%m-%d')
self.filter = "ga:medium=" + filter
self.metrics = metrics
Example models.py: #has the following function
import google_auth
service = googleauth.initialize_service()
def total_visit(self):
object = AnalyticsData.objects.get(utm_source=self.utm_source)
trial = Query(object.date.startdate, object.date.enddate, object.utm_source, ga:sessions")
result = service.data().ga().get(ids = 'ga:<your-profile-id>', start_date = trial.startdate, end_date = trial.enddate, filters= trial.filter, metrics = trial.metrics).execute()
total_visit = result.get('rows')
<yr save command, ColumnName.object.create(data=total_visit) goes here>