• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pywikibot.input函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pywikibot.input函数的典型用法代码示例。如果您正苦于以下问题:Python input函数的具体用法?Python input怎么用?Python input使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了input函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: main

def main():
    options = {}

    local_args = pywikibot.handleArgs()
    genFactory = pagegenerators.GeneratorFactory()
    site = pywikibot.Site()

    for arg in local_args:
        if arg.startswith('-enable'):
            if len(arg) == 7:
                options['enablePage'] = pywikibot.input(
                    u'Would you like to check if the bot should run or not?')
            else:
                options['enablePage'] = arg[8:]
        elif arg.startswith('-disambig'):
            if len(arg) == 9:
                options['disambigPage'] = pywikibot.input(
                    u'In which page should the bot save the disambig pages?')
            else:
                options['disambigPage'] = arg[10:]
        elif arg == '-always':
            options['always'] = True
        else:
            genFactory.handleArg(arg)

    generator = genFactory.getCombinedGenerator()

    # If the generator is not given, use the default one
    if not generator:
        generator = site.lonelypages(total=genFactory.limit)

    bot = LonelyPagesBot(generator, **options)
    bot.run()
开发者ID:anrao91,项目名称:pywikibot-core,代码行数:33,代码来源:lonelypages.py


示例2: main

def main(*args): # bot_class=InfoboxMigratingBot
    options = {}
    local_args = pywikibot.handle_args(args)
    genFactory = pagegenerators.GeneratorFactory()
    for arg in local_args:
        if genFactory.handleArg(arg):
            continue
        if arg.startswith('-'):
            arg, sep, value = arg.partition(':')
            if value != '':
                options[arg[1:]] = value if not value.isdigit() else int(value)
            else:
                options[arg[1:]] = True

    while not options.get('template', None):
        options['template'] = pywikibot.input(
            'Enter the template you would like to work on:')
        options['new_template'] = pywikibot.input(
            'Enter the template to replace the previous one:')

    if not options.get('new_template', None):
        options['new_template'] = options['template']

    generator = genFactory.getCombinedGenerator()
    if not generator:
        genFactory.handleArg('-transcludes:%s' % options['template'])
        generator = genFactory.getCombinedGenerator()

    bot = InfoboxMigratingBot(generator=generator, **options) # bot_class
    bot.run()
开发者ID:matejsuchanek,项目名称:pywikibot-scripts,代码行数:30,代码来源:migrate_infobox.py


示例3: main

def main(*args):

    # Process global args and prepare generator args parser
    local_args = pywikibot.handle_args(args)
    googlecat = False
    collectionid = False
    for arg in local_args:
        if arg.startswith('-googlecat'):
            if len(arg) == 10:
                googlecat = pywikibot.input(
                    u'Please enter the category you want to work on:')
            else:
                googlecat = arg[11:]
        elif arg.startswith('-collectionid'):
            if len(arg) == 13:
                collectionid = pywikibot.input(
                    u'Please enter the collectionid you want to work on:')
            else:
                collectionid = arg[14:]
        #else:
        #    generator_factory.handleArg(arg)

    if googlecat and collectionid:
        imageFindBot = ImageFindBot(googlecat, collectionid)
        imageFindBot.run()
    else:
        pywikibot.output(u'Usage: pwb.py add_google_images.py -googlecat:<category name> -collectionid:Q<123>')
开发者ID:multichill,项目名称:toollabs,代码行数:27,代码来源:add_google_images.py


示例4: main

def main():
    opts = {}
    for arg in pywikibot.handleArgs():
        if arg.startswith('-hours:'):
            opts['hours'] = float(arg[7:])
            opts['no_repeat'] = False
        elif arg.startswith('-delay:'):
            opts['delay'] = int(arg[7:])
        elif arg.startswith('-page'):
            if len(arg) == 5:
                opts['page'] = pywikibot.input(
                    u'Which page do you want to change?')
            else:
                opts['page'] = arg[6:]
        elif arg.startswith('-text'):
            if len(arg) == 5:
                opts['text'] = pywikibot.input(
                    u'What text do you want to substitute?')
            else:
                opts['text'] = arg[6:]
        elif arg == '-user':
            opts['user'] = True
        elif arg.startswith('-summary'):
            if len(arg) == len('-summary'):
                opts['summary'] = pywikibot.input(u'Enter the summary:')
            else:
                opts['summary'] = arg[9:]
        else:
            pywikibot.showHelp('clean_sandbox')
            return

    bot = SandboxBot(**opts)
    bot.run()
开发者ID:anrao91,项目名称:pywikibot-core,代码行数:33,代码来源:clean_sandbox.py


示例5: main

def main():
    genFactory = pagegenerators.GeneratorFactory()
    pageName = ''
    summary = None
    always = False
    undelete = False
    generator = None

    # read command line parameters
    local_args = pywikibot.handleArgs()
    mysite = pywikibot.Site()

    for arg in local_args:
        if arg == '-always':
            always = True
        elif arg.startswith('-summary'):
            if len(arg) == len('-summary'):
                summary = pywikibot.input(u'Enter a reason for the deletion:')
            else:
                summary = arg[len('-summary:'):]
        elif arg.startswith('-images'):
            pywikibot.output('\n\03{lightred}-image option is deprecated. '
                             'Please use -imageused instead.\03{default}\n')
            local_args.append('-imageused' + arg[7:])
        elif arg.startswith('-undelete'):
            undelete = True
        else:
            genFactory.handleArg(arg)
            found = arg.find(':') + 1
            if found:
                pageName = arg[found:]

        if not summary:
            if pageName:
                if arg.startswith('-cat') or arg.startswith('-subcats'):
                    summary = i18n.twtranslate(mysite, 'delete-from-category',
                                               {'page': pageName})
                elif arg.startswith('-links'):
                    summary = i18n.twtranslate(mysite, 'delete-linked-pages',
                                               {'page': pageName})
                elif arg.startswith('-ref'):
                    summary = i18n.twtranslate(mysite, 'delete-referring-pages',
                                               {'page': pageName})
                elif arg.startswith('-imageused'):
                    summary = i18n.twtranslate(mysite, 'delete-images',
                                               {'page': pageName})
            elif arg.startswith('-file'):
                summary = i18n.twtranslate(mysite, 'delete-from-file')
    generator = genFactory.getCombinedGenerator()
    # We are just deleting pages, so we have no need of using a preloading
    # page generator to actually get the text of those pages.
    if generator:
        if summary is None:
            summary = pywikibot.input(u'Enter a reason for the %sdeletion:'
                                      % ['', 'un'][undelete])
        bot = DeletionRobot(generator, summary, always, undelete)
        bot.run()
    else:
        # Show help text from the top of this file
        pywikibot.showHelp()
开发者ID:APerson241,项目名称:pywikibot-core,代码行数:60,代码来源:delete.py


示例6: main

def main(args):
    '''
    Main loop.
    '''
    start_id = 3
    end_id = 18473
    single_id = 0

    site = pywikibot.getSite('commons', 'commons')


    for arg in pywikibot.handleArgs():
        if arg.startswith('-start_id'):
            if len(arg) == 9:
                start_id = pywikibot.input(u'What is the id of the search page you want to start at?')
            else:
                start_id = arg[10:]
        elif arg.startswith('-end_id'):
            if len(arg) == 7:
                end_id = pywikibot.input(u'What is the id of the search page you want to end at?')
            else:
                end_id = arg[8:]
	elif arg.startswith('-id'):
	    if len(arg) == 3:
		single_id = pywikibot.input(u'What is the id of the search page you want to transfer?')
	    else:
		single_id = arg[4:]

    if single_id > 0:
        start_id = single_id
        end_id = int(single_id) + 1

    reader =  HABSReader(start=int(start_id), end=int(end_id))
    bot = data_ingestion.DataIngestionBot(reader, "%(item_title)s - LOC - %(resources_id)s.%(_ext)s", "HABS data ingestion layout", pywikibot.getSite('commons', 'commons'))
    bot.run()
开发者ID:multichill,项目名称:toollabs,代码行数:35,代码来源:habs_bot.py


示例7: main

def main():
	lang=pywikibot.getSite().language()
	start = None
	# Loading the arguments
	for arg in pywikibot.handleArgs():
		if arg.startswith('-lang'):
			if len(arg) == 5:
				lang = pywikibot.input(u'What language do you want to use?')
			else:
				lang = arg[6:]
		elif arg.startswith('-start'):
			if len(arg) == 6:
				start = pywikibot.input(u'What article do you want to start with?')
			else:
				start = arg[7:]
	
	bot = o2wVillageData()
	# bot.tl2Dict(bot.extractTemplate(u"""{{Infocaseta Așezare
# | nume = Bogdănești
# | alt_nume = 
# | tip_asezare = Sat
# | imagine = 
# | imagine_dimensiune = 250px
# | imagine_descriere = Bogdănești
# | stemă = 
# | hartă = 
# | pushpin_map = 
# | pushpin_label_position = right
# | tip_subdiviziune = Țară
# | nume_subdiviziune = {{ROU}}
# | tip_subdiviziune1 = [[Județele României|Județ]]
# | nume_subdiviziune1 = [[județul Vaslui|Vaslui]]
# | tip_subdiviziune3 = [[Comunele României|Comună]]
# | nume_subdiviziune3 = [[Comuna Bogdănești, Vaslui|Bogdănești]]
# | titlu_atestare = Prima atestare
# | atestare = 
# | suprafață_totală_km2 = 
# | altitudine = 
# | latd = 46
# | latm = 26
# | lats = 58
# | latNS = N
# | longd = 27
# | longm = 43
# | longs = 36
# | longEV = E
# | recensământ = 2002
# | populație = 
# | populație_note_subsol = 
# | tip_cod_poștal = [[Cod poștal]]
# | codpoștal = 
# | camp_gol_nume =
# | camp_gol_info = 
# }}

# '''Bogdănești''' este o localitate în [[județul Vaslui]], [[Moldova]], [[România]]
# """, u"Infocaseta Așezare"))
	# print bot._dict
	bot.putCoordOnWiki(lang, start)
开发者ID:edgarskos,项目名称:wikiro,代码行数:59,代码来源:osm2wiki_template.py


示例8: main

def main():
    xmlFilename = None
    always = False
    ignorepdf = False
    limit = None
    namespaces = []
    generator = None
    summary = None

    # Process global args and prepare generator args parser
    local_args = pywikibot.handleArgs()
    genFactory = pagegenerators.GeneratorFactory()

    for arg in local_args:
        if arg.startswith('-namespace:'):
            try:
                namespaces.append(int(arg[11:]))
            except ValueError:
                namespaces.append(arg[11:])
        elif arg.startswith('-summary:'):
            summary = arg[9:]
        elif arg == '-always':
            always = True
        elif arg == '-ignorepdf':
            ignorepdf = True
        elif arg.startswith('-limit:'):
            limit = int(arg[7:])
        elif arg.startswith('-xmlstart'):
            if len(arg) == 9:
                xmlStart = pywikibot.input(
                    u'Please enter the dumped article to start with:')
            else:
                xmlStart = arg[10:]
        elif arg.startswith('-xml'):
            if len(arg) == 4:
                xmlFilename = pywikibot.input(
                    u'Please enter the XML dump\'s filename:')
            else:
                xmlFilename = arg[5:]
        else:
            genFactory.handleArg(arg)

    if xmlFilename:
        try:
            xmlStart
        except NameError:
            xmlStart = None
        generator = XmlDumpPageGenerator(xmlFilename, xmlStart, namespaces)
    if not generator:
        generator = genFactory.getCombinedGenerator()
    if not generator:
        # syntax error, show help text from the top of this file
        pywikibot.showHelp()
        return
    generator = pagegenerators.PreloadingGenerator(generator, step=50)
    generator = pagegenerators.RedirectFilterPageGenerator(generator)
    bot = ReferencesRobot(generator, always, limit, ignorepdf, summary)
    bot.run()
开发者ID:fdeco,项目名称:pywikibot-core,代码行数:58,代码来源:reflinks.py


示例9: main

def main(*args):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: list of unicode
    """
    xmlFilename = None
    xmlStart = None
    options = {}
    generator = None

    # Process global args and prepare generator args parser
    local_args = pywikibot.handle_args(args)
    genFactory = pagegenerators.GeneratorFactory()

    for arg in local_args:
        if arg.startswith('-summary:'):
            options['summary'] = arg[9:]
        elif arg == '-always':
            options['always'] = True
        elif arg == '-ignorepdf':
            options['ignorepdf'] = True
        elif arg.startswith('-limit:'):
            options['limit'] = int(arg[7:])
        elif arg.startswith('-xmlstart'):
            if len(arg) == 9:
                xmlStart = pywikibot.input(
                    u'Please enter the dumped article to start with:')
            else:
                xmlStart = arg[10:]
        elif arg.startswith('-xml'):
            if len(arg) == 4:
                xmlFilename = pywikibot.input(
                    u'Please enter the XML dump\'s filename:')
            else:
                xmlFilename = arg[5:]
        else:
            genFactory.handleArg(arg)

    if xmlFilename:
        generator = XmlDumpPageGenerator(xmlFilename, xmlStart,
                                         genFactory.namespaces)
    if not generator:
        generator = genFactory.getCombinedGenerator()
    if not generator:
        pywikibot.bot.suggest_help(missing_generator=True)
        return False
    if not genFactory.nopreload:
        generator = pagegenerators.PreloadingGenerator(generator)
    generator = pagegenerators.RedirectFilterPageGenerator(generator)
    bot = ReferencesRobot(generator, **options)
    bot.run()
    return True
开发者ID:Darkdadaah,项目名称:pywikibot-core,代码行数:56,代码来源:reflinks.py


示例10: main

def main(*args):
    """
    Main function. Grab a generator and pass it to the bot to work on
    """
    series = None
    report = None
    for arg in pywikibot.handle_args(args):
        if arg.startswith('-series:'):
            if len(arg) == 8:
                series = pywikibot.input(
                        u'Please enter the Q id of the series to work on:')
            else:
                series = arg[8:]
        elif arg.startswith('-report:'):
            if len(arg) == 8:
                report = pywikibot.input(
                        u'Please enter the name of the page to report on:')
            else:
                report = arg[8:]


    basequery = u"""SELECT DISTINCT ?item WHERE {
  ?item wdt:P31 wd:Q21191270 .
  ?item wdt:P179 wd:%s .
  MINUS { ?item wdt:P345 [] . ?item wdt:P1191 []}
  #{ ?item wdt:P155 ?otheritem } UNION { ?item wdt:P156 ?otheritem }
  #?otheritem wdt:P345 [] .
  }"""

    repo = pywikibot.Site().data_repository()
    if series:
        query = basequery % (series,)
        generator = pagegenerators.PreloadingItemGenerator(pagegenerators.WikidataSPARQLPageGenerator(query,
                                                                                                      site=repo))
        imdbFinderBot = IMDBFinderBot(generator, series)
        imdbFinderBot.run()
    else:
        seriesquery = u"""SELECT DISTINCT ?item WHERE {
  ?episode wdt:P31 wd:Q21191270 .
  ?episode wdt:P179 ?item .
  MINUS { ?episode wdt:P345 [] . ?item wdt:P1191 []}
  { ?episode wdt:P155 ?otheritem } UNION { ?episode wdt:P156 ?otheritem }
  ?otheritem wdt:P345 [] .
  ?otheritem wdt:P179 ?item .
  }"""
        seriesgen = pagegenerators.PreloadingItemGenerator(pagegenerators.WikidataSPARQLPageGenerator(seriesquery,
                                                                                                      site=repo))
        for seriespage in seriesgen:
            series = seriespage.title()
            query = basequery % (series,)
            generator = pagegenerators.PreloadingItemGenerator(pagegenerators.WikidataSPARQLPageGenerator(query,
                                                                                                          site=repo))
            imdbFinderBot = IMDBFinderBot(generator, series)
            imdbFinderBot.run()
开发者ID:multichill,项目名称:toollabs,代码行数:54,代码来源:imdb_finder.py


示例11: main

def main():
    # if -file is not used, this temporary array is used to read the page title.
    pageTitle = []
    page = None
    gen = None
    interwiki = False
    keep_name = False
    targetLang = None
    targetFamily = None

    for arg in pywikibot.handleArgs():
        if arg == '-interwiki':
            interwiki = True
        elif arg.startswith('-keepname'):
            keep_name = True
        elif arg.startswith('-tolang:'):
            targetLang = arg[8:]
        elif arg.startswith('-tofamily:'):
            targetFamily = arg[10:]
        elif arg.startswith('-file'):
            if len(arg) == 5:
                filename = pywikibot.input(
                    u'Please enter the list\'s filename: ')
            else:
                filename = arg[6:]
            gen = pagegenerators.TextfilePageGenerator(filename)
        else:
            pageTitle.append(arg)

    if not gen:
        # if the page title is given as a command line argument,
        # connect the title's parts with spaces
        if pageTitle != []:
            pageTitle = ' '.join(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 = 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 = pywikibot.getSite('commons', 'commons')
    else:
        if not targetLang:
            targetLang = pywikibot.getSite().language
        if not targetFamily:
            targetFamily = pywikibot.getSite().family
        targetSite = pywikibot.getSite(targetLang, targetFamily)
    bot = ImageTransferBot(gen, interwiki=interwiki, targetSite=targetSite,
                           keep_name=keep_name)
    bot.run()
开发者ID:Rodehi,项目名称:GFROS,代码行数:54,代码来源:imagetransfer.py


示例12: matcher

def matcher():
    match1 = wikipedia.input(" Rakitra 1:")
    match2 = wikipedia.input(" Rakitra 2:")
    outfile= wikipedia.input(" Rakitra avoaka:")
    infile1 = file('%s.txt'%match1,'r').readlines()
    infile2 = file('%s.txt'%match2,'r').read()
    outfile = file('%s.txt'%outfile,'a')

    for line in infile1:
        if infile2.find(line)!=-1:
            infile2 = infile2.replace('%s\n'%line,'')
    outfile.write(infile2)
开发者ID:Webysther,项目名称:botjagwar,代码行数:12,代码来源:batcher.py


示例13: askForCaptcha

 def askForCaptcha(self, url):
     """Show the user a CAPTCHA image and return the answer."""
     try:
         import webbrowser
         pywikibot.output(u'Opening CAPTCHA in your web browser...')
         webbrowser.open(url)
         return pywikibot.input(
             u'What is the solution of the CAPTCHA that is shown in your web browser?')
     except:
         pywikibot.output(u'Error in opening web browser: %s'
                           % sys.exc_info()[0])
         return pywikibot.input(
             u'What is the solution of the CAPTCHA at %s ?' % url)
开发者ID:azatoth,项目名称:pywikipedia,代码行数:13,代码来源:terminal_interface.py


示例14: askForCaptcha

    def askForCaptcha(self, url):
        """Show the user a CAPTCHA image and return the answer."""
        try:
            import webbrowser

            pywikibot.output("Opening CAPTCHA in your web browser...")
            if webbrowser.open(url):
                return pywikibot.input("What is the solution of the CAPTCHA that is shown in " "your web browser?")
            else:
                raise
        except:
            pywikibot.output("Error in opening web browser: %s" % sys.exc_info()[0])
            pywikibot.output("Please copy this url to your web browser and open it:\n %s" % url)
            return pywikibot.input("What is the solution of the CAPTCHA at this url ?")
开发者ID:Annie201,项目名称:pywikibot-core,代码行数:14,代码来源:terminal_interface_base.py


示例15: main

def main(*args):
    """Extracting file page information of images to work on and initiate matching."""
    images = []
    other_family = u''
    other_lang = u''
    imagePageA = None
    imagePageB = None

    # Read commandline parameters.
    local_args = pywikibot.handle_args(args)

    for arg in local_args:
        if arg.startswith('-otherfamily:'):
            if len(arg) == len('-otherfamily:'):
                other_family = pywikibot.input(u'What family do you want to use?')
            else:
                other_family = arg[len('-otherfamily:'):]
        elif arg.startswith('-otherlang:'):
            if len(arg) == len('-otherlang:'):
                other_lang = pywikibot.input(u'What language do you want to use?')
            else:
                other_lang = arg[len('otherlang:'):]
        else:
            images.append(arg)

    if len(images) != 2:
        pywikibot.showHelp('match_images')
        pywikibot.error('Require two images to work on.')
        return

    else:
        pass

    imagePageA = pywikibot.page.FilePage(pywikibot.Site(),
                                         images[0])
    if other_lang:
        if other_family:
            imagePageB = pywikibot.page.FilePage(pywikibot.Site(
                                                 other_lang, other_family),
                                                 images[1])
        else:
            imagePageB = pywikibot.page.FilePage(pywikibot.Site(
                                                 other_lang),
                                                 images[1])
    else:
        imagePageB = pywikibot.page.FilePage(pywikibot.Site(),
                                             images[1])

    match_image_pages(imagePageA, imagePageB)
开发者ID:donkaban,项目名称:pywiki-bot,代码行数:49,代码来源:match_images.py


示例16: main

def main(*args):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: list of unicode
    """
    options = {}
    # Process global arguments to determine desired site
    local_args = pywikibot.handle_args(args)

    # This factory is responsible for processing command line arguments
    # that are also used by other scripts and that determine on which pages
    # to work on.
    genFactory = pagegenerators.GeneratorFactory()

    # Parse command line arguments
    for arg in local_args:

        # Catch the pagegenerators options
        if genFactory.handleArg(arg):
            continue  # nothing to do here

        # Now pick up your own options
        arg, sep, value = arg.partition(':')
        option = arg[1:]
        if option in ('summary', 'text'):
            if not value:
                pywikibot.input('Please enter a value for ' + arg)
            options[option] = value
        # take the remaining options as booleans.
        # You will get a hint if they aren't pre-definded in your bot class
        else:
            options[option] = True

    gen = genFactory.getCombinedGenerator()
    if gen:
        # The preloading generator is responsible for downloading multiple
        # pages from the wiki simultaneously.
        gen = pagegenerators.PreloadingGenerator(gen)
        # pass generator and private options to the bot
        bot = BasicBot(gen, **options)
        bot.run()  # guess what it does
        return True
    else:
        pywikibot.bot.suggest_help(missing_generator=True)
        return False
开发者ID:PersianWikipedia,项目名称:pywikibot-core,代码行数:49,代码来源:basic.py


示例17: main

def main(*args):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: list of unicode
    """
    opts = {}
    unknown_args = []

    local_args = pywikibot.handle_args(args)
    for arg in local_args:
        option, sep, value = arg.partition(':')
        if option.startswith('-'):
            option = option[1:]
            if option == 'filename':
                opts[option] = value or pywikibot.input(
                    'Enter the filename: ')
                continue
            elif option == 'storepath':
                opts[option] = os.path.abspath(value) or pywikibot.input(
                    'Enter the store path: ')
                continue
            elif option == 'revision':
                opts[option] = value or pywikibot.input(
                    'Enter the revision of the dump: ')
                continue

        unknown_args += [arg]

    missing = []
    if 'filename' not in opts:
        missing += ['-filename']

    if missing or unknown_args:
        pywikibot.bot.suggest_help(missing_parameters=missing,
                                   unknown_parameters=unknown_args)
        return 1

    site = pywikibot.Site()
    opts['wikiname'] = site.dbName()

    bot = DownloadDumpBot(**opts)
    bot.run()

    return 0
开发者ID:magul,项目名称:pywikibot-core,代码行数:48,代码来源:download_dump.py


示例18: process_filename

    def process_filename(self):
        """Return base filename portion of self.url"""
        # Isolate the pure name
        filename = self.url
        # Filename may be either a local file path or a URL
        if "://" in filename:
            # extract the path portion of the URL
            filename = urlparse.urlparse(filename).path
        filename = os.path.basename(filename)

        if self.useFilename:
            filename = self.useFilename
        if not self.keepFilename:
            pywikibot.output(
                u"The filename on the target wiki will default to: %s"
                % filename)
            # FIXME: these 2 belong somewhere else, presumably in family
            forbidden = '/' # to be extended
            allowed_formats = (u'gif', u'jpg', u'jpeg', u'mid', u'midi',
                               u'ogg', u'png', u'svg', u'xcf', u'djvu')
            # ask until it's valid
            while True:
                newfn = pywikibot.input(
                            u'Enter a better name, or press enter to accept:')
                if newfn == "":
                    newfn = filename
                    break
                ext = os.path.splitext(newfn)[1].lower().strip('.')
                # are any chars in forbidden also in newfn?
                invalid = set(forbidden) & set(newfn)
                if invalid:
                    c = "".join(invalid)
                    print "Invalid character(s): %s. Please try again" % c
                    continue
                if ext not in allowed_formats:
                    choice = pywikibot.inputChoice(
                        u"File format is not one of [%s], but %s. Continue?"
                         % (u' '.join(allowed_formats), ext),
                            ['yes', 'no'], ['y', 'N'], 'N')
                    if choice == 'n':
                        continue
                break
            if newfn != '':
                filename = newfn
        # A proper description for the submission.
        pywikibot.output(u"The suggested description is:")
        pywikibot.output(self.description)
        if self.verifyDescription:
            newDescription = u''
            choice = pywikibot.inputChoice(
                u'Do you want to change this description?',
                ['Yes', 'No'], ['y', 'N'], 'n')
            if choice == 'y':
                import editarticle
                editor = editarticle.TextEditor()
                newDescription = editor.edit(self.description)
            # if user saved / didn't press Cancel
            if newDescription:
                self.description = newDescription
        return filename
开发者ID:azatoth,项目名称:pywikipedia,代码行数:60,代码来源:upload.py


示例19: login

    def login(self, retry=False):
        if not self.password:
            # As we don't want the password to appear on the screen, we set
            # password = True
            self.password = pywikibot.input(
                u'Password for user %(name)s on %(site)s (no characters will '
                u'be shown):' % {'name': self.username, 'site': self.site},
                password=True)
#        self.password = self.password.encode(self.site.encoding())

        pywikibot.output(u"Logging in to %(site)s as %(name)s"
                         % {'name': self.username, 'site': self.site})
        try:
            cookiedata = self.getCookie()
        except pywikibot.data.api.APIError as e:
            pywikibot.error(u"Login failed (%s)." % e.code)
            if retry:
                self.password = None
                return self.login(retry=True)
            else:
                return False
        self.storecookiedata(cookiedata)
        pywikibot.log(u"Should be logged in now")
##        # Show a warning according to the local bot policy
##   FIXME: disabled due to recursion; need to move this to the Site object after
##   login
##        if not self.botAllowed():
##            logger.error(
##                u"Username '%(name)s' is not listed on [[%(page)s]]."
##                 % {'name': self.username,
##                    'page': botList[self.site.family.name][self.site.code]})
##            logger.error(
##"Please make sure you are allowed to use the robot before actually using it!")
##            return False
        return True
开发者ID:bjonesin,项目名称:pywikibot-core,代码行数:35,代码来源:login.py


示例20: main

def main(*args):
    """
    Do a query and have the bot process the items
    :param args:
    :return:
    """

    # The queries for paintings without a creator, all or a specific collection
    query = u'SELECT ?item WHERE { ?item wdt:P31 wd:Q3305213 . MINUS { ?item wdt:P170 [] } }'
    querycollection = u"""SELECT ?item WHERE { ?item wdt:P31 wd:Q3305213 .
                                 ?item wdt:P195 wd:%s .
                                 MINUS { ?item wdt:P170 [] }
                           }"""

    for arg in pywikibot.handle_args(args):
        print arg
        if arg.startswith('-collectionid'):
            if len(arg) == 13:
                collectionid = pywikibot.input(
                        u'Please enter the collectionid you want to work on:')
            else:
                collectionid = arg[14:]
            query = querycollection % (collectionid,)

    repo = pywikibot.Site().data_repository()
    generator = pagegenerators.PreloadingItemGenerator(pagegenerators.WikidataSPARQLPageGenerator(query, site=repo))

    paintingBot = PaintingBot(generator, change=False)
    paintingBot.run()
开发者ID:multichill,项目名称:toollabs,代码行数:29,代码来源:painting_add_creator.py



注:本文中的pywikibot.input函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pywikibot.inputChoice函数代码示例发布时间:2022-05-26
下一篇:
Python pywikibot.handle_args函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap