Revision: 8539
Author: xqt
Date: 2010-09-12 17:06:21 +0000 (Sun, 12 Sep 2010)
Log Message:
-----------
wikipedia.Page(asLink=False) is implemented for easier merging to rewrite branch
Modified Paths:
--------------
trunk/pywikipedia/wikipedia.py
Modified: trunk/pywikipedia/wikipedia.py
===================================================================
--- trunk/pywikipedia/wikipedia.py 2010-09-12 15:56:11 UTC (rev 8538)
+++ trunk/pywikipedia/wikipedia.py 2010-09-12 17:06:21 UTC (rev 8539)
@@ -432,15 +432,47 @@
"""Return the character encoding used on this Page's wiki Site."""
return self._site.encoding()
- def title(self, underscore = False, savetitle = False, decode=False):
+ def title(self, underscore=False, savetitle=False, decode=False,
+ withNamespace=True,
+ withSection=True, asUrl=False, asLink=False,
+ allowInterwiki=True, forceInterwiki=False, textlink=False,
+ as_filename=False):
"""Return the title of this Page, as a Unicode string.
+ @param underscore: if true, replace all ' ' characters with '_'
+ @param withNamespace: - not implemented yet -
+ @param withSection: - not implemented yet -
+ @param asUrl: - not implemented yet -
+ @param asLink: if true, return the title in the form of a wikilink
+ @param allowInterwiki: (only used if asLink is true) if true, format
+ the link as an interwiki link if necessary
+ @param forceInterwiki: (only used if asLink is true) if true, always
+ format the link as an interwiki link
+ @param textlink: (only used if asLink is true) if true, place a ':'
+ before Category: and Image: links
+ @param as_filename: - not implemented yet -
+
If underscore is True, replace all ' ' characters with '_'.
If savetitle is True, encode any wiki syntax in the title.
If decode is True, decodes the section title
"""
title = self._title
- if decode:
+ if asLink:
+ if allowInterwiki and (forceInterwiki or self._site != getSite()):
+ colon = ""
+ if textlink:
+ colon = ":"
+ if self._site.family != getSite().family \
+ and self._site.family.name != self._site.lang:
+ return u'[[%s%s:%s:%s]]' % (colon, self._site.family.name,
+ self._site.lang, title)
+ else:
+ return u'[[%s%s:%s]]' % (colon, self._site.lang, title)
+ elif textlink and (self.isImage() or self.isCategory()):
+ return u'[[:%s]]' % title
+ else:
+ return u'[[%s]]' % title
+ if decode or asLink:
begin = title.find('#')
if begin != -1:
anchor = self.section(underscore = underscore, decode = True)
@@ -449,7 +481,7 @@
except TypeError:
print title, begin, anchor
raise
- if savetitle:
+ if savetitle or asLink:
# Ensure there's no wiki syntax in the title
title = title.replace(u"''", u'%27%27')
if underscore:
@@ -514,6 +546,7 @@
"""Return a more complete string representation."""
return "%s{%s}" % (self.__class__.__name__, str(self))
+ #@deprecated("Page.title(asLink=True)")
def aslink(self, forceInterwiki=False, textlink=False, noInterwiki=False):
"""Return a string representation in the form of a wikilink.
@@ -525,24 +558,11 @@
interwiki links and internal links to the Category: and Image:
namespaces will be preceded by a : character).
+ DEPRECATED to merge to rewrite branch:
+ use self.title(asLink=True) instead.
"""
- if not noInterwiki and (forceInterwiki or self._site != getSite()):
- colon = ""
- if textlink:
- colon = ":"
- if self._site.family != getSite().family \
- and self._site.family.name != self._site.lang:
- return u'[[%s%s:%s:%s]]' % (colon, self._site.family.name,
- self._site.lang,
- self.title(savetitle=True,
- decode=True))
- else:
- return u'[[%s%s:%s]]' % (colon, self._site.lang,
- self.title(savetitle=True, decode=True))
- elif textlink and (self.isImage() or self.isCategory()):
- return u'[[:%s]]' % self.title(savetitle=True, decode=True)
- else:
- return u'[[%s]]' % self.title(savetitle=True, decode=True)
+ return self.title(asLink=True, forceInterwiki=forceInterwiki,
+ allowInterwiki=not noInterwiki, textlink=textlink)
def autoFormat(self):
"""Return (dictName, value) if title is in date.autoFormat dictionary.
Revision: 8538
Author: xqt
Date: 2010-09-12 15:56:11 +0000 (Sun, 12 Sep 2010)
Log Message:
-----------
New -cleanup option: like -force but only removes interwiki links to non-existent or empty pages. (requested by bug #3062725 and bug #2744607) -- update from trunk
Modified Paths:
--------------
branches/rewrite/scripts/interwiki.py
Modified: branches/rewrite/scripts/interwiki.py
===================================================================
--- branches/rewrite/scripts/interwiki.py 2010-09-12 15:51:14 UTC (rev 8537)
+++ branches/rewrite/scripts/interwiki.py 2010-09-12 15:56:11 UTC (rev 8538)
@@ -183,6 +183,9 @@
alternatives actually exists.
(note: without ending colon)
+ -cleanup like -force but only removes interwiki links to non-existent
+ or empty pages.
+
-select ask for each link whether it should be included before
changing any page. This is useful if you want to remove
invalid interwiki links and if you do multiple hints of
@@ -599,6 +602,8 @@
followredirect = True
initialredirect = False
force = False
+ cleanup = False
+ remove = []
maxquerysize = 60
same = False
skip = set()
@@ -647,6 +652,8 @@
f.close()
elif arg == '-force':
self.force = True
+ elif arg == '-cleanup':
+ self.cleanup = True
elif arg == '-same':
self.same = True
elif arg == '-wiktionary':
@@ -1098,7 +1105,6 @@
self.makeForcedStop(counter)
return False
-
if page in self.foundIn:
# not new
self.foundIn[page].append(linkingPage)
@@ -1306,6 +1312,7 @@
# todo list.
if not page.exists():
+ globalvar.remove.append(page.title(asLink=True, forceInterwiki=True))
if not globalvar.quiet:
pywikibot.output(u"NOTE: %s does not exist" % page)
if page == self.originPage:
@@ -1369,6 +1376,7 @@
# must be behind the page.isRedirectPage() part
# otherwise a redirect error would be raised
if page.isEmpty() and not page.isCategory():
+ globalvar.remove.append(page.title(asLink=True, forceInterwiki=True))
if not globalvar.quiet:
pywikibot.output(u"NOTE: %s is empty. Skipping." % page)
if page == self.originPage:
@@ -1443,6 +1451,7 @@
sys.exit()
iw = ()
elif page.isEmpty() and not page.isCategory():
+ globalvar.remove.append(page.title(asLink=True, forceInterwiki=True))
if not globalvar.quiet:
pywikibot.output(u"NOTE: %s is empty; ignoring it and its interwiki links" % page)
# Ignore the interwiki links
@@ -1787,12 +1796,20 @@
# When running in autonomous mode without -force switch, make sure we don't remove any items, but allow addition of the new ones
if globalvar.autonomous and not globalvar.force and len(removing) > 0:
for rmsite in removing:
- if rmsite != page.site: # Sometimes sites have an erroneous link to itself as an interwiki
- rmPage = old[rmsite]
- new[rmsite] = old[rmsite] #put it to new means don't delete it
- pywikibot.output(u"WARNING: %s is either deleted or has a mismatching disambiguation state." % rmPage)
+ # Sometimes sites have an erroneous link to itself as an
+ # interwiki
+ if rmsite == page.site:
+ continue
+ rmPage = old[rmsite]
+ #put it to new means don't delete it
+ if not globalvar.cleanup or \
+ rmPage.title(asLink=True, forceInterwiki=True) not in globalvar.remove:
+ new[rmsite] = rmPage
+ pywikibot.output(
+ u"WARNING: %s is either deleted or has a mismatching disambiguation state."
+ % rmPage)
# Re-Check what needs to get done
- mods, mcomment, adding, removing, modifying = compareLanguages(old, new, insite = page.site)
+ mods, mcomment, adding, removing, modifying = compareLanguages(old, new, insite=page.site)
if not mods:
if not globalvar.quiet:
Revision: 8536
Author: xqt
Date: 2010-09-12 14:50:49 +0000 (Sun, 12 Sep 2010)
Log Message:
-----------
New -cleanup option: like -force but only removes interwiki links to non-existent or empty pages. (requested by bug #3062725 and bug #2744607)
Modified Paths:
--------------
trunk/pywikipedia/interwiki.py
Modified: trunk/pywikipedia/interwiki.py
===================================================================
--- trunk/pywikipedia/interwiki.py 2010-09-12 14:43:02 UTC (rev 8535)
+++ trunk/pywikipedia/interwiki.py 2010-09-12 14:50:49 UTC (rev 8536)
@@ -183,6 +183,9 @@
alternatives actually exists.
(note: without ending colon)
+ -cleanup like -force but only removes interwiki links to non-existent
+ or empty pages.
+
-select ask for each link whether it should be included before
changing any page. This is useful if you want to remove
invalid interwiki links and if you do multiple hints of
@@ -572,6 +575,8 @@
followredirect = True
initialredirect = False
force = False
+ cleanup = False
+ remove = []
maxquerysize = 60
same = False
skip = set()
@@ -620,6 +625,8 @@
f.close()
elif arg == '-force':
self.force = True
+ elif arg == '-cleanup':
+ self.cleanup = True
elif arg == '-same':
self.same = True
elif arg == '-wiktionary':
@@ -1278,6 +1285,7 @@
# todo list.
if not page.exists():
+ globalvar.remove.append(page.aslink(forceInterwiki=True))
if not globalvar.quiet or pywikibot.verbose:
pywikibot.output(u"NOTE: %s does not exist. Skipping." % page.aslink(True))
if page == self.originPage:
@@ -1341,6 +1349,7 @@
# must be behind the page.isRedirectPage() part
# otherwise a redirect error would be raised
if page.isEmpty() and not page.isCategory():
+ globalvar.remove.append(page.aslink(forceInterwiki=True))
if not globalvar.quiet or pywikibot.verbose:
pywikibot.output(u"NOTE: %s is empty. Skipping." % page.aslink(True))
if page == self.originPage:
@@ -1415,6 +1424,7 @@
sys.exit()
iw = ()
elif page.isEmpty() and not page.isCategory():
+ globalvar.remove.append(page.aslink(forceInterwiki=True))
if not globalvar.quiet or pywikibot.verbose:
pywikibot.output(u"NOTE: %s is empty; ignoring it and its interwiki links" % page.aslink(True))
# Ignore the interwiki links
@@ -1815,15 +1825,24 @@
# Check what needs to get done
mods, mcomment, adding, removing, modifying = compareLanguages(old, new, insite = page.site())
- # When running in autonomous mode without -force switch, make sure we don't remove any items, but allow addition of the new ones
+ # When running in autonomous mode without -force switch, make sure we
+ # don't remove any items, but allow addition of the new ones
if globalvar.autonomous and not globalvar.force and len(removing) > 0:
for rmsite in removing:
- if rmsite != page.site(): # Sometimes sites have an erroneous link to itself as an interwiki
- rmPage = old[rmsite]
- new[rmsite] = old[rmsite] #put it to new means don't delete it
- pywikibot.output(u"WARNING: %s is either deleted or has a mismatching disambiguation state." % rmPage.aslink(True))
+ # Sometimes sites have an erroneous link to itself as an
+ # interwiki
+ if rmsite == page.site():
+ continue
+ rmPage = old[rmsite]
+ #put it to new means don't delete it
+ if not globalvar.cleanup or \
+ rmPage.aslink(forceInterwiki=True) not in globalvar.remove:
+ new[rmsite] = rmPage
+ pywikibot.output(
+ u"WARNING: %s is either deleted or has a mismatching disambiguation state."
+ % rmPage.aslink(True))
# Re-Check what needs to get done
- mods, mcomment, adding, removing, modifying = compareLanguages(old, new, insite = page.site())
+ mods, mcomment, adding, removing, modifying = compareLanguages(old, new, insite=page.site())
if not mods:
if not globalvar.quiet or pywikibot.verbose:
@@ -1857,7 +1876,7 @@
if removing and removing != [page.site()]: # Allow for special case of a self-pointing interwiki link
self.problem(u'Found incorrect link to %s in %s'% (",".join([x.lang for x in removing]), page.aslink(True)), createneed = False)
ask = True
- if globalvar.force:
+ if globalvar.force or globalvar.cleanup:
ask = False
if globalvar.confirm and not globalvar.always:
ask = True
Revision: 8533
Author: xqt
Date: 2010-09-12 12:45:14 +0000 (Sun, 12 Sep 2010)
Log Message:
-----------
import wikipedia as pywikibot for merging to rewrite branch
Modified Paths:
--------------
trunk/pywikipedia/imagetransfer.py
trunk/pywikipedia/inline_images.py
Modified: trunk/pywikipedia/imagetransfer.py
===================================================================
--- trunk/pywikipedia/imagetransfer.py 2010-09-12 12:44:49 UTC (rev 8532)
+++ trunk/pywikipedia/imagetransfer.py 2010-09-12 12:45:14 UTC (rev 8533)
@@ -30,7 +30,8 @@
__version__='$Id$'
import re, sys, md5, urllib
-import wikipedia, upload, config, pagegenerators
+import wikipedia as pywikibot
+import upload, config, pagegenerators
copy_message = {
'ar':u"هذه الصورة تم نقلها من %s. الوصف الأصلي كان:\r\n\r\n%s",
@@ -136,6 +137,7 @@
},
}
+
class ImageTransferBot:
def __init__(self, generator, targetSite = None, interwiki = False):
self.generator = generator
@@ -149,10 +151,10 @@
This function is used by imagetransfer.py and by copy_table.py
"""
sourceSite = sourceImagePage.site()
- if debug: print "--------------------------------------------------"
+ if debug: print "-" * 50
if debug: print "Found image: %s"% imageTitle
url = sourceImagePage.fileUrl().encode('utf-8')
- wikipedia.output(u"URL should be: %s" % url)
+ pywikibot.output(u"URL should be: %s" % url)
# localize the text that should be printed on the image description page
try:
description = sourceImagePage.get()
@@ -161,17 +163,20 @@
for old, new in licenseTemplates[(sourceSite.sitename(), self.targetSite.sitename())].iteritems():
new = '{{%s}}' % new
old = re.compile('{{%s}}' % old)
- description = wikipedia.replaceExcept(description, old, new, ['comment', 'math', 'nowiki', 'pre'])
+ description = pywikibot.replaceExcept(description, old, new,
+ ['comment', 'math',
+ 'nowiki', 'pre'])
- description = wikipedia.translate(self.targetSite, copy_message) % (sourceSite, description)
+ description = pywikibot.translate(self.targetSite, copy_message) \
+ % (sourceSite, description)
description += '\n\n' + sourceImagePage.getFileVersionHistoryTable()
# add interwiki link
if sourceSite.family == self.targetSite.family:
description += "\r\n\r\n" + sourceImagePage.aslink(forceInterwiki = True)
- except wikipedia.NoPage:
+ except pywikibot.NoPage:
description=''
print "Image does not exist or description page is empty."
- except wikipedia.IsRedirectPage:
+ except pywikibot.IsRedirectPage:
description=''
print "Image description page is redirect."
else:
@@ -180,14 +185,14 @@
targetFilename = bot.run()
if targetFilename and self.targetSite.family.name == 'commons' and self.targetSite.lang == 'commons':
# upload to Commons was successful
- reason = wikipedia.translate(sourceSite, nowCommonsMessage)
+ reason = pywikibot.translate(sourceSite, nowCommonsMessage)
# try to delete the original image if we have a sysop account
if sourceSite.family.name in config.sysopnames and sourceSite.lang in config.sysopnames[sourceSite.family.name]:
if sourceImagePage.delete(reason):
return
if sourceSite.lang in nowCommonsTemplate and sourceSite.family.name in config.usernames and sourceSite.lang in config.usernames[sourceSite.family.name]:
# add the nowCommons template.
- wikipedia.output(u'Adding nowCommons template to %s' % sourceImagePage.title())
+ pywikibot.output(u'Adding nowCommons template to %s' % sourceImagePage.title())
sourceImagePage.put(sourceImagePage.get() + '\n\n' + nowCommonsTemplate[sourceSite.lang] % targetFilename, comment = nowCommonsMessage[sourceSite.lang])
def showImageList(self, imagelist):
@@ -195,10 +200,10 @@
image = imagelist[i]
#sourceSite = sourceImagePage.site()
print "-"*60
- wikipedia.output(u"%s. Found image: %s"% (i, image.aslink()))
+ pywikibot.output(u"%s. Found image: %s"% (i, image.aslink()))
try:
# Show the image description page's contents
- wikipedia.output(image.get(throttle=False))
+ pywikibot.output(image.get(throttle=False))
# look if page already exists with this name.
# TODO: consider removing this: a different image of the same
# name may exist on the target wiki, and the bot user may want
@@ -206,21 +211,20 @@
try:
# Maybe the image is on the target site already
targetTitle = '%s:%s' % (self.targetSite.image_namespace(), image.title().split(':', 1)[1])
- targetImage = wikipedia.Page(self.targetSite, targetTitle)
+ targetImage = pywikibot.Page(self.targetSite, targetTitle)
targetImage.get(throttle=False)
- wikipedia.output(u"Image with this name is already on %s." % self.targetSite)
+ pywikibot.output(u"Image with this name is already on %s." % self.targetSite)
print "-"*60
- wikipedia.output(targetImage.get(throttle=False))
+ pywikibot.output(targetImage.get(throttle=False))
sys.exit()
- except wikipedia.NoPage:
+ except pywikibot.NoPage:
# That's the normal case
pass
- except wikipedia.IsRedirectPage:
- wikipedia.output(u"Description page on target wiki is redirect?!")
+ except pywikibot.IsRedirectPage:
+ pywikibot.output(u"Description page on target wiki is redirect?!")
- except wikipedia.NoPage:
+ except pywikibot.NoPage:
break
-
print "="*60
def run(self):
@@ -230,7 +234,7 @@
for linkedPage in page.interwiki():
imagelist += linkedPage.imagelinks(followRedirects = True)
elif page.isImage():
- imagePage = wikipedia.ImagePage(page.site(), page.title())
+ imagePage = pywikibot.ImagePage(page.site(), page.title())
imagelist = [imagePage]
else:
imagelist = page.imagelinks(followRedirects = True)
@@ -241,21 +245,22 @@
# no need to query the user, only one possibility
todo = 0
else:
- wikipedia.output(u"Give the number of the image to transfer.")
- todo = wikipedia.input(u"To end uploading, press enter:")
+ pywikibot.output(u"Give the number of the image to transfer.")
+ todo = pywikibot.input(u"To end uploading, press enter:")
if not todo:
break
todo = int(todo)
if todo in range(len(imagelist)):
if imagelist[todo].fileIsOnCommons():
- wikipedia.output(u'The image is already on Wikimedia Commons.')
+ pywikibot.output(u'The image is already on Wikimedia Commons.')
else:
self.transferImage(imagelist[todo], debug = False)
# remove the selected image from the list
imagelist = imagelist[:todo] + imagelist[todo + 1:]
else:
- wikipedia.output(u'No such image number.')
+ pywikibot.output(u'No such image number.')
+
def main():
# if -file is not used, this temporary array is used to read the page title.
pageTitle = []
@@ -265,7 +270,7 @@
targetLang = None
targetFamily = None
- for arg in wikipedia.handleArgs():
+ for arg in pywikibot.handleArgs():
if arg == '-interwiki':
interwiki = True
elif arg.startswith('-tolang:'):
@@ -274,7 +279,7 @@
targetFamily = arg[10:]
elif arg.startswith('-file'):
if len(arg) == 5:
- filename = wikipedia.input(u'Please enter the list\'s filename: ')
+ filename = pywikibot.input(u'Please enter the list\'s filename: ')
else:
filename = arg[6:]
gen = pagegenerators.TextfilePageGenerator(filename)
@@ -286,23 +291,23 @@
# connect the title's parts with spaces
if pageTitle != []:
pageTitle = ' '.join(pageTitle)
- page = wikipedia.Page(wikipedia.getSite(), pageTitle)
+ page = pywikibot.Page(pywikibot.getSite(), pageTitle)
# if no page title was given as an argument, and none was
# read from a file, query the user
if not page:
- pageTitle = wikipedia.input(u'Which page to check:')
- page = wikipedia.Page(wikipedia.getSite(), pageTitle)
+ pageTitle = pywikibot.input(u'Which page to check:')
+ page = pywikibot.Page(pywikibot.getSite(), pageTitle)
# generator which will yield only a single Page
gen = iter([page])
if not targetLang and not targetFamily:
- targetSite = wikipedia.getSite('commons', 'commons')
+ targetSite = pywikibot.getSite('commons', 'commons')
else:
if not targetLang:
- targetLang = wikipedia.getSite().language
+ targetLang = pywikibot.getSite().language
if not targetFamily:
- targetFamily = wikipedia.getSite().family
- targetSite = wikipedia.Site(targetLang, targetFamily)
+ targetFamily = pywikibot.getSite().family
+ targetSite = pywikibot.Site(targetLang, targetFamily)
bot = ImageTransferBot(gen, interwiki = interwiki, targetSite = targetSite)
bot.run()
@@ -310,4 +315,4 @@
try:
main()
finally:
- wikipedia.stopme()
+ pywikibot.stopme()
Modified: trunk/pywikipedia/inline_images.py
===================================================================
--- trunk/pywikipedia/inline_images.py 2010-09-12 12:44:49 UTC (rev 8532)
+++ trunk/pywikipedia/inline_images.py 2010-09-12 12:45:14 UTC (rev 8533)
@@ -24,13 +24,14 @@
__version__='$Id$'
-import wikipedia, pagegenerators, catlib, weblinkchecker, upload
import sys, re
+import wikipedia as pywikibot
+import pagegenerators, catlib, weblinkchecker, upload
# This is required for the text that is shown when you run this script
# with the parameter -help.
docuReplacements = {
- '¶ms;': pagegenerators.parameterHelp,
+ '¶ms;': pagegenerators.parameterHelp,
}
msg = {
@@ -58,9 +59,10 @@
# depends on the variable self.touch_redirects.
text = page.get()
originalText = text
- for url in weblinkchecker.weblinksIn(text, withoutBracketed = True):
+ for url in weblinkchecker.weblinksIn(text,
+ withoutBracketed=True):
filename = url.split('/')[-1]
- description = wikipedia.translate(wikipedia.getSite(), msg) % url
+ description = pywikibot.translate(pywikibot.getSite(), msg) % url
bot = upload.UploadRobot(url, description = description)
# TODO: check duplicates
#filename = bot.uploadImage()
@@ -69,11 +71,11 @@
# only save if there were changes
#if text != originalText:
# page.put(text)
- except wikipedia.NoPage:
+ except pywikibot.NoPage:
print "Page %s does not exist?!" % page.aslink()
- except wikipedia.IsRedirectPage:
+ except pywikibot.IsRedirectPage:
print "Page %s is a redirect; skipping." % page.aslink()
- except wikipedia.LockedPage:
+ except pywikibot.LockedPage:
print "Page %s is locked?!" % page.aslink()
def main():
@@ -88,18 +90,18 @@
# to work on.
genFactory = pagegenerators.GeneratorFactory()
- for arg in wikipedia.handleArgs():
+ for arg in pywikibot.handleArgs():
if not genFactory.handleArg(arg):
pageTitle.append(arg)
if pageTitle:
# work on a single page
- page = wikipedia.Page(wikipedia.getSite(), ' '.join(pageTitle))
+ page = pywikibot.Page(pywikibot.getSite(), ' '.join(pageTitle))
gen = iter([page])
if not gen:
gen = genFactory.getCombinedGenerator()
if not gen:
- wikipedia.showHelp('inline_images')
+ pywikibot.showHelp('inline_images')
else:
preloadingGen = pagegenerators.PreloadingGenerator(gen)
bot = InlineImagesRobot(preloadingGen)
@@ -109,4 +111,4 @@
try:
main()
finally:
- wikipedia.stopme()
+ pywikibot.stopme()
Revision: 8532
Author: xqt
Date: 2010-09-12 12:44:49 +0000 (Sun, 12 Sep 2010)
Log Message:
-----------
fix for class constructor;
import wikipedia as pywikibot for merging to rewrite branch
Modified Paths:
--------------
trunk/pywikipedia/logindata.py
Modified: trunk/pywikipedia/logindata.py
===================================================================
--- trunk/pywikipedia/logindata.py 2010-09-12 12:20:11 UTC (rev 8531)
+++ trunk/pywikipedia/logindata.py 2010-09-12 12:44:49 UTC (rev 8532)
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
-#Usable example module: Use of pywikipedia as a
+# Usable example module: Use of pywikipedia as a
# library.
#
# Looks up the path to pywikipedia (pywikipedia_path)
@@ -22,7 +22,8 @@
# for now, we live with it.
cwd=os.getcwd()
os.chdir(settings.pywikipedia_path)
-import wikipedia, login
+import wikipedia as pywikibot
+import login
from simple_family import Family
os.chdir(cwd)
@@ -30,14 +31,26 @@
"""An example class that uses pywikipedia as a library.
usage example:
- from logindata import LoginData, wikipedia
+ from logindata import LoginData, pywikibot
target_wiki=LoginData( ... ) # for example, fill in from a settings file, or use code to generate, or ...
site=target_wiki.login()
- page=wikipedia.Page(site,"Main Page")
+ page=pywikibot.Page(site,"Main Page")
"""
-
def __init__(
+ self,
+ name='MY_NAME_FOR_THIS_SERVER',
+ protocol='http',
+ server='www.my_server.com',
+ scriptpath='/my/script/path/',
+ version='1.13.2',
+ lang='en',
+ encoding='utf-8',
+ user='MY_BOT_USER',
+ password='MY_SECRET_PASSWORD',
+ RversionTab=None,
+ api_supported=False
+ ):
"""
paramaters:
name: arbitrary name. Pick something easy to remember
@@ -54,20 +67,6 @@
password: password for this user
"""
-
- self,
- name='MY_NAME_FOR_THIS_SERVER',
- protocol='http',
- server='www.my_server.com',
- scriptpath='/my/script/path/',
- version='1.13.2',
- lang='en',
- encoding='utf-8',
- user='MY_BOT_USER',
- password='MY_SECRET_PASSWORD',
- RversionTab=None,
- api_supported=False
- ):
self.lang=lang
self.user=user
self.password=password
@@ -86,7 +85,7 @@
def login(self):
"""Attempt to log in on the site described
by this class. Returns a pywikipedia site object"""
- self.site=wikipedia.Site(
+ self.site=pywikibot.Site(
code=self.lang,
fam=self.family,
user=self.user
Revision: 8531
Author: xqt
Date: 2010-09-12 12:20:11 +0000 (Sun, 12 Sep 2010)
Log Message:
-----------
import wikipedia as pywikibot for merging to rewrite branch
Modified Paths:
--------------
trunk/pywikipedia/imageharvest.py
Modified: trunk/pywikipedia/imageharvest.py
===================================================================
--- trunk/pywikipedia/imageharvest.py 2010-09-12 12:19:44 UTC (rev 8530)
+++ trunk/pywikipedia/imageharvest.py 2010-09-12 12:20:11 UTC (rev 8531)
@@ -19,7 +19,8 @@
__version__='$Id$'
import re, sys, os
-import wikipedia, upload
+import wikipedia as pywikibot
+import upload
def get_imagelinks(url):
# Given a URL, get all images linked to by the page at that URL.
@@ -31,7 +32,7 @@
relativepath=relativepath[:len(relativepath)-1]
relativepath="/".join(relativepath)
links = []
- uo = wikipedia.MyURLopener
+ uo = pywikibot.MyURLopener
file = uo.open(url)
text = file.read()
file.close()
@@ -56,22 +57,26 @@
if url == '':
if image_url:
- url = wikipedia.input(u"What URL range should I check (use $ for the part that is changeable)")
+ url = pywikibot.input(
+ u"What URL range should I check (use $ for the part that is changeable)")
else:
- url = wikipedia.input(u"From what URL should I get the images?")
+ url = pywikibot.input(
+ u"From what URL should I get the images?")
if image_url:
minimum=1
maximum=99
- answer= wikipedia.input(u"What is the first number to check (default: 1)")
+ answer= pywikibot.input(
+ u"What is the first number to check (default: 1)")
if answer:
minimum=int(answer)
- answer= wikipedia.input(u"What is the last number to check (default: 99)")
+ answer= pywikibot.input(
+ u"What is the last number to check (default: 99)")
if answer:
maximum=int(answer)
if not desc:
- basicdesc = wikipedia.input(
+ basicdesc = pywikibot.input(
u"What text should be added at the end of the description of each image from this url?")
else:
basicdesc = desc
@@ -86,18 +91,22 @@
ilinks = get_imagelinks(url)
for image in ilinks:
- answer = wikipedia.inputChoice(u'Include image %s?' % image, ['yes', 'no', 'stop'], ['y', 'N', 's'], 'N')
+ answer = pywikibot.inputChoice(u'Include image %s?'
+ % image, ['yes', 'no', 'stop'],
+ ['y', 'N', 's'], 'N')
if answer == 'y':
- desc = wikipedia.input(u"Give the description of this image:")
+ desc = pywikibot.input(u"Give the description of this image:")
categories = []
while True:
- cat = wikipedia.input(u"Specify a category (or press enter to end adding categories)")
+ cat = pywikibot.input(
+ u"Specify a category (or press enter to end adding categories)")
if not cat.strip(): break
if ":" in cat:
categories.append("[["+cat+"]]")
else:
categories.append("[["+mysite.namespace(14)+":"+cat+"]]")
- desc = desc + "\r\n\r\n" + basicdesc + "\r\n\r\n" + "\r\n".join(categories)
+ desc = desc + "\r\n\r\n" + basicdesc + "\r\n\r\n" + \
+ "\r\n".join(categories)
uploadBot = upload.UploadRobot(image, description = desc)
uploadBot.run()
elif answer == 's':
@@ -108,7 +117,7 @@
shown = False
desc = []
- for arg in wikipedia.handleArgs():
+ for arg in pywikibot.handleArgs():
if arg == "-pattern":
image_url = True
elif arg == "-shown":
@@ -122,7 +131,7 @@
desc = ' '.join(desc)
fileformats = ('jpg', 'jpeg', 'png', 'gif', 'svg', 'ogg')
- mysite = wikipedia.getSite()
+ mysite = pywikibot.getSite()
main(url, image_url, desc)
finally:
- wikipedia.stopme()
+ pywikibot.stopme()