我们从Python开源项目中,提取了以下36个代码示例,用于说明如何使用version.__version__()。
def version(bot, event, *args): """get the version of the bot and dependencies (admin-only)""" version_info = [] version_info.append(_("Bot Version: **{}**").format(__version__)) # hangoutsbot version_info.append(_("Python Version: **{}**").format(sys.version.split()[0])) # python # display extra version information only if user is an admin admins_list = bot.get_config_suboption(event.conv_id, 'admins') if event.user.id_.chat_id in admins_list: # depedencies modules = args or [ "aiohttp", "appdirs", "emoji", "hangups", "telepot" ] for module_name in modules: try: _module = importlib.import_module(module_name) version_info.append(_("* {} **{}**").format(module_name, _module.__version__)) except(ImportError, AttributeError): pass yield from bot.coro_send_message(event.conv, "\n".join(version_info))
def usage(): print "SMOP compiler version " + __version__ print """Usage: smop [options] file-list Options: -V --version -X --exclude=FILES Ignore files listed in comma-separated list FILES. Can be used several times. -S --syntax-errors=FILES Ignore syntax errors in comma-separated list of FILES. Can be used several times. -S. Always gnore syntax errors -d --dot=REGEX For functions whose names match REGEX, save debugging information in "dot" format (see www.graphviz.org). You need an installation of graphviz to use --dot option. Use "dot" utility to create a pdf file. For example: $ python main.py fastsolver.m -d "solver|cbest" $ dot -Tpdf -o resolve_solver.pdf resolve_solver.dot -h --help -o --output=FILENAME By default create file named a.py -o- --output=- Use standard output -s --strict Stop on the first error -v --verbose """
def parse_args(args): """ Parse arguments for the NDWI algorithm """ desc = 'Beachfront Algorithm: NDWI (v%s)' % __version__ dhf = argparse.ArgumentDefaultsHelpFormatter parser = argparse.ArgumentParser(description=desc, formatter_class=dhf) parser.add_argument('-i', '--input', help='Input image (1 or 2 files)', required=True, action='append') parser.add_argument('-b', '--bands', help='Band numbers for Green and NIR bands', default=[1, 1], nargs=2, type=int) parser.add_argument('--outdir', help='Save intermediate files to this dir (otherwise temp)', default='') h = 'Basename to give to output files (no extension, defaults to first input filename' parser.add_argument('--basename', help=h, default=None) parser.add_argument('--l8bqa', help='Landat 8 Quality band (used to mask clouds)') parser.add_argument('--coastmask', help='Mask non-coastline areas', default=defaults['coastmask'], action='store_true') parser.add_argument('--minsize', help='Minimum coastline size', default=defaults['minsize'], type=float) parser.add_argument('--close', help='Close line strings within given pixels', default=defaults['close'], type=int) parser.add_argument('--simple', help='Simplify using tolerance in map units', default=None, type=float) parser.add_argument('--smooth', help='Smoothing from 0 (none) to 1.33 (no corners', default=defaults['smooth'], type=float) h = '0: Quiet, 1: Debug, 2: Info, 3: Warn, 4: Error, 5: Critical' parser.add_argument('--verbose', help=h, default=2, type=int) parser.add_argument('--version', help='Print version and exit', action='version', version=__version__) return parser.parse_args(args)
def help(self, argv=('jonah',)): """Output the help screen""" output = "Jonah {} -- ".format(version.__version__) output += "USAGE:\n" output += " {} <COMMAND>, where <COMMMAND> is one of the following:\n".format(argv[0]) commands = {"General": ['init', 'build', 'clean_build', 'cleanup', 'version'], "Development": ['develop', 'reload', 'shell', 'stop', 'test', 'compilemessages'], "Deployment": ['stage', 'deploy', 'tag', 'direct_deploy']} for group_name in commands.keys(): output += "\n {}:\n".format(group_name) for command_name in commands[group_name]: command_help = textwrap.wrap(getattr(self, command_name).__doc__, 56) output += " - {}\t{}\n".format(command_name.ljust(12), command_help[0]) if len(command_help) > 1: for additional_line in command_help[1:]: output += (" " * 20) + "\t" + additional_line + "\n" return output # Helper Methods ###################################################################################################
def load_about(self): self.about_text_property = "" + \ "PyWallet version: %s\n" % (__version__) + \ "Project source code and info available on GitHub at: \n" + \ "[color=00BFFF][ref=github]" + \ self.project_page_property + \ "[/ref][/color]"
def configure_sentry(in_debug=False): """ Configure the Raven client, or create a dummy one if `in_debug` is `True`. """ key = 'eaee971c463b49678f6f352dfec497a9' # the public DSN URL is not available on the Python client # so we're exposing the secret and will be revoking it on abuse # https://github.com/getsentry/raven-python/issues/569 secret = '4f37fdbde03a4753b78abb84d11f45ab' project_id = '191660' dsn = 'https://{key}:{secret}@sentry.io/{project_id}'.format( key=key, secret=secret, project_id=project_id) if in_debug: client = DebugRavenClient() else: client = Client(dsn=dsn, release=__version__) # adds context for Android devices if platform == 'android': from jnius import autoclass Build = autoclass("android.os.Build") VERSION = autoclass('android.os.Build$VERSION') android_os_build = { 'model': Build.MODEL, 'brand': Build.BRAND, 'device': Build.DEVICE, 'manufacturer': Build.MANUFACTURER, 'version_release': VERSION.RELEASE, } client.user_context({'android_os_build': android_os_build}) # Logger.error() to Sentry # https://docs.sentry.io/clients/python/integrations/logging/ handler = SentryHandler(client) handler.setLevel(LOG_LEVELS.get('error')) setup_logging(handler) return client
def process_args(): ''' Validates the application arguments, and resolves the arguments into a Namespace object. :rtype: Namespace object with argument values mapped to destination properties. The mapping is defined in the argument parser. ''' parser = argparse.ArgumentParser(description="User Sync Test from Adobe") parser.add_argument("-v", "--version", action="version", version="%(prog)s " + APP_VERSION) parser.add_argument("-c", "--test-suite-config-filename", help="main test suite config filename.", metavar="filename", dest="config_filename", default=DEFAULT_CONFIG_FILENAME) parser.add_argument("-g", "--test-group-name", help="test group to limit testing to.", metavar="group", dest="test_group_name", default=None) parser.add_argument("-t", "--test", help="test name", metavar="name of test", dest="test_name", default=None) parser.add_argument("-l", "--live", help="sets the user-sync-test tool in Live mode, which directs user-sync to communicate " "with the ummapi server, and overwrites any recorded session with the communication " "and output from this new live session. (Playback mode is the default mode.)", action="store_true", dest="live_mode") parser.add_argument("-p", "--playback", help="sets the user-sync-test tool in Playback mode, which suppresses any communication " "with the umapi server, and instead plays back the responses recorded from the server " "during the last live session. (This is the default mode.)", action="store_false", dest="live_mode") parser.set_defaults(live_mode=False) return parser.parse_args()
def SOAPUserAgent(): return "SOAPpy " + __version__ + " (pywebsvcs.sf.net)"
def version_string(self): return '<a href="http://pywebsvcs.sf.net">' + \ 'SOAPpy ' + __version__ + '</a> (Python ' + \ sys.version.split()[0] + ')'
def main(): log_filename = "keyrotator" + time.strftime("-%Y-%m-%d-%H%M") + ".log" logging.basicConfig(filename=log_filename, level=logging.INFO) logging.getLogger("").addHandler(logging.StreamHandler()) logging.info("Logging established in %s.", log_filename) dispatch(__doc__, version=__version__)
def run(self): host, port = self.checkArgs() log.info("Running PwnUp {}".format(version.__version__)) connection = self.chooseClientType(host, port) interaction = self.interact(connection) self.saveFile(connection, interaction) log.info("Client Written to {}".format(self.filename))
def show_version(): """ Show program version an quit :return: """ from version import __version__ print("{} {}".format(__package__, __version__)) sys.exit(0)
def _init(engine): global Interface, EVENT, Control, FunctionControl, Label, Textbox, Text, load_image, __version__, initialized import env env.engine = engine from interface import Interface, EVENT from control import Control, FunctionControl, Label, Textbox from util import Text, load_image from version import __version__ initialized = True
def update_user(cls, user): """ Creates a new User object with current methods and attributes and fills in the new users attributes with attributes from the old user object. :param user: The User object which is to be updated. :type user: User """ new_user = User(__version__, user.name, user.save_path, user.post_limit, user.avoid_duplicates, user.download_videos, user.download_images, user.name_downloads_by, user.user_added) cls.update_extras(user, new_user) return new_user
def update_subreddit(cls, sub): """ Creates a new Subreddit object with current methods and attributes and fills in the new subs attributes with the attributes from the old subreddit object. :param sub: The outdated subreddit object wich is to be updated. :type sub: Subreddit """ new_sub = Subreddit(__version__, sub.name, sub.save_path, sub.post_limit, sub.avoid_duplicates, sub.download_videos, sub.download_images, sub.subreddit_save_method, sub.name_downloads_by, sub.user_added) cls.update_extras(sub, new_sub) return new_sub
def __init__(self, sub_list, black_list, top_sort_method, score_limit, sample_size, existing_users, save_path, imgur_client, previously_found): """ A class that searches supplied subreddits for top posts (of the user set period) and collects the names of users who have submitted posts that scored above the set score limit. It will then download the user specified sample size of posts and display them on the second page. Also has methods to add any found users to the main download users list as well as methods to exclude certain users that the user wishes not to include. Parts of this class work similar to the parts of the main program, but on a smaller scale. For instance, when a user is found an instance of the User class is created for them with preset settings supplied. This class is only used temporarily and if the user is added to the main list the instance is destroyed and a new instance made with the proper overall settings. :param sub_list: The sub list supplied by the UserFinderGUI which is to be searched for top posts :param black_list: A list of users who are not to be included even if their posts reach the score limit :param top_sort_method: The period of top posts to be searched (eg: day, week, etc.) :param score_limit: The limit that post scores must be above to be considered :param sample_size: The number of posts that are to be downloaded if the conditions are met :param existing_users: A list of users already added to the main GUI lists that will be emitted from search :param save_path: The save path of the special UserFinder directory where the user finder posts are stored :param imgur_client: An instance of the imgure client that is supplied to temporarily created users :param previously_found: A list of users that have been previously found and will not be included in the search """ super().__init__() self.reddit = praw.Reddit(user_agent='python:DownloaderForReddit:%s (by /u/MalloyDelacroix)' % __version__, client_id='frGEUVAuHGL2PQ', client_secret=None) self.sub_list = sub_list self.black_list = black_list self.top_sort_method = top_sort_method self.score_limit = score_limit self.sample_size = sample_size self.existing_users = existing_users self.save_path = save_path self.imgur_client = imgur_client self.previously_found_users = previously_found self.validated_subreddits = [] self.found_users = [] self.queue = Queue() self.content_count = 0
def __init__(self): """ Opens the "about" dialog box which displays the licensing information """ QtWidgets.QDialog.__init__(self) self.setupUi(self) self.settings_manager = Core.Injector.get_settings_manager() geom = self.settings_manager.about_dialog_geom self.restoreGeometry(geom if geom is not None else self.saveGeometry()) self.buttonBox.accepted.connect(self.accept) pixmap = QtGui.QPixmap('Images/RedditDownloaderIcon.png') pixmap = pixmap.scaled(QtCore.QSize(183, 186), QtCore.Qt.KeepAspectRatio) self.logo_label.setFixedWidth(80) self.logo_label.setFixedHeight(82) self.logo_label.setPixmap(pixmap) self.logo_label.setScaledContents(True) self.info_label.setText('Version: %s\nAuthor: Kyle H' % __version__) self.info_label.setScaledContents(True) self.link_label.setText('Homepage: <a href="https://github.com/MalloyDelacroix/DownloaderForReddit">Downloader for Reddit</a>') self.link_label.setToolTip('https://github.com/MalloyDelacroix/DownloaderForReddit') self.license_box.setOpenExternalLinks(True) self.total_downloads_label.setText("Total Downloads: %s" % self.settings_manager.total_files_downloaded)
def __init__(self, name, ip, port, *args, **kwargs): """Constructor. Args: name: (str) name of Flask service ip: (str) IP address to bind HTTP server port: (int) TCP port for HTTP server to listen """ super(HttpServer, self).__init__(name, *args, **kwargs) # Fixup the root path for Flask so it can find templates/* root_path = os.path.abspath(os.path.dirname(__file__)) logging.debug('Setting root_path for Flask: %s', root_path) self.root_path = root_path self.targets = config.CollectorConfig() self.ip = ip self.port = port self.start_time = time.time() self.setup_time = 0 self.scheduler = BackgroundScheduler( daemon=True, executors=self.EXECUTORS) self.collection = None self.add_url_rule('/', 'index', self.index_handler) self.add_url_rule('/status', 'status', self.status_handler) self.add_url_rule('/latency', 'latency', self.latency_handler) self.add_url_rule('/influxdata', 'influxdata', self.influxdata_handler) self.add_url_rule('/quitquit', 'quitquit', self.shutdown_handler) logging.info('Starting Llama Collector, version %s', __version__)
def version(self): """Print out the version number and exit""" self.printout(version.__version__)
def __call__(self, parser, namespace, values, option_string): try: import version print('kdtool version {}, {}.'.format( version.__version__, version.__info__)) except ImportError: print('kdtool, development build or manual installation.') exit(0) # Create our argument parser.
def main(): puts(colored.green("Pgrepup %s" % __version__)) try: dispatch(__doc__) except KeyboardInterrupt: puts("\n" + colored.red('Execution aborted')) exit(0)
def main(): parser = argparse.ArgumentParser(prog='zibra', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("-v", "--version", help="Installed zibra version", action="version", version="%(prog)s " + str(version.__version__)) subparsers = parser.add_subparsers(title='[sub-commands]', dest='command', parser_class=ArgumentParserWithDefaults) # extract parser_extract = subparsers.add_parser('extract', help='Create an empty poredb database') parser_extract.add_argument('directory', metavar='directory', help='The name of the database.') parser_extract.add_argument('--basecaller', metavar='basecaller', default='ONT Albacore Sequencing Software', help='The name of the basecaller') parser_extract.set_defaults(func=run_subtool) # callers parser_extract = subparsers.add_parser('basecaller', help='Display basecallers in files') parser_extract.add_argument('directory', metavar='directory', help='Directory of FAST5 files.') parser_extract.set_defaults(func=run_subtool) # demultiplex parser_demultiplex = subparsers.add_parser('demultiplex', help='Run demultiplex') parser_demultiplex.add_argument('fasta', metavar='fasta', help='Undemultiplexed FASTA file.') parser_demultiplex.add_argument('--threads', type=int, default=8, help='Number of threads') parser_demultiplex.add_argument('--prefix', help='Prefix for demultiplexed files') parser_demultiplex.add_argument('--no-remove-directory', dest='no_remove_directory', action='store_true') parser_demultiplex.set_defaults(func=run_subtool) # minion parser_minion = subparsers.add_parser('minion', help='Run demultiplex') parser_minion.add_argument('scheme', metavar='scheme', help='The name of the scheme.') parser_minion.add_argument('sample', metavar='sample', help='The name of the sample.') parser_minion.add_argument('--normalise', dest='normalise', type=int, default=100, help='Normalise down to moderate coverage to save runtime.') parser_minion.add_argument('--threads', type=int, default=8, help='Number of threads') parser_minion.add_argument('--scheme-directory', metavar='scheme_directory', default='/zibra/zika-pipeline/schemes', help='Default scheme directory') parser_minion.add_argument('--max-haplotypes', type=int, default=1000000, metavar='max_haplotypes', help='max-haplotypes value for nanopolish') parser_minion.add_argument('--read-file', metavar='read_file', help='Use alternative FASTA/FASTQ file to <sample>.fasta') parser_minion.add_argument('--skip-nanopolish', action='store_true') parser_minion.set_defaults(func=run_subtool) # import """parser_import = subparsers.add_parser('import', help='Import files into a poredb database') parser_import.add_argument('db', metavar='DB', help='The poredb database.') parser_import.add_argument('fofn', metavar='FOFN', help='A file containing a list of file names.') parser_import.add_argument('--alternate-path', metavar='alternate_path') parser_import.set_defaults(func=run_subtool) """ args = parser.parse_args() if args.quiet: logger.setLevel(logging.ERROR) args.func(parser, args)
def main(): """Main entry point""" # Build default paths for files. dirs = appdirs.AppDirs("hangupsbot", "hangupsbot") default_log_path = os.path.join(dirs.user_data_dir, "hangupsbot.log") default_cookies_path = os.path.join(dirs.user_data_dir, "cookies.json") default_config_path = os.path.join(dirs.user_data_dir, "config.json") default_memory_path = os.path.join(dirs.user_data_dir, "memory.json") # Configure argument parser parser = argparse.ArgumentParser( prog="hangupsbot", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("-d", "--debug", action="store_true", help=_("log detailed debugging messages")) parser.add_argument("--log", default=default_log_path, help=_("log file path")) parser.add_argument("--cookies", default=default_cookies_path, help=_("cookie storage path")) parser.add_argument("--memory", default=default_memory_path, help=_("memory storage path")) parser.add_argument("--config", default=default_config_path, help=_("config storage path")) parser.add_argument("--retries", default=5, type=int, help=_("Maximum disconnect / reconnect retries before " "quitting")) parser.add_argument("--version", action="version", version="%(prog)s {}".format(version.__version__), help=_("show program\"s version number and exit")) args = parser.parse_args() # Create all necessary directories. for path in [args.log, args.cookies, args.config, args.memory]: directory = os.path.dirname(path) if directory and not os.path.isdir(directory): try: os.makedirs(directory) except OSError as err: sys.exit(_("Failed to create directory: %s"), err) # If there is no config file in user data directory, copy default one there if not os.path.isfile(args.config): try: shutil.copy( os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "config.json")), args.config) except (OSError, IOError) as err: sys.exit(_("Failed to copy default config file: %s"), err) configure_logging(args) # initialise the bot bot = HangupsBot(args.cookies, args.config, args.memory, args.retries) # start the bot bot.run()
def __init__(self, user_list, subreddit_list, queue, unfinished_downloads_list): """ Class that does the main part of the work for the program. This class contains the praw instance that is used for actually extracting the content from reddit. When an instance is created all settings parameters must be supplied to the instance. This class also calls the necessary functions of the other classes and completes the downloads. :param user_list: The actual list of User objects contained in the user ListModel class displayed in the GUI :param subreddit_list: The actual list of Subreddit objects contained in the subreddit ListModel class displayed in the GUI. If this class is initialized to only run a user list, this parameter is None :param queue: The queue that text is added to in order to update the GUI The rest of teh parameters are all configuration options that are set in the settings dialog """ super().__init__() self._r = praw.Reddit(user_agent='python:DownloaderForReddit:%s (by /u/MalloyDelacroix)' % __version__, client_id='frGEUVAuHGL2PQ', client_secret=None) self.settings_manager = Core.Injector.get_settings_manager() self.user_list = user_list self.subreddit_list = subreddit_list self.queue = queue self.validated_objects = Queue() self.validated_subreddits = [] self.failed_downloads = [] self.downloaded_users = {} self.unfinished_downloads = [] self.user_run = True if self.user_list is not None else False self.post_limit = self.settings_manager.post_limit self.save_path = self.settings_manager.save_directory self.subreddit_sort_method = self.settings_manager.subreddit_sort_method self.subreddit_sort_top_method = self.settings_manager.subreddit_sort_top_method self.restrict_date = self.settings_manager.restrict_by_date self.restrict_by_score = self.settings_manager.restrict_by_score self.restrict_score_method = self.settings_manager.score_limit_operator self.restrict_score_limit = self.settings_manager.post_score_limit self.unfinished_downloads_list = unfinished_downloads_list self.load_undownloaded_content = self.settings_manager.save_undownloaded_content self.queued_posts = Queue() self.run = True self.start_extractor() self.start_downloader() self.download_number = 0