Python __init__ 模块,__version__() 实例源码

我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用__init__.__version__()

项目:RiboCode    作者:xzt41    | 项目源码 | 文件源码
def parsing_plot_orf_density():
    parser = argparse.ArgumentParser(
        description="This script is designed for plot the P-site profile of specified ORF."
    )
    parser.add_argument("-a","--annot_dir",dest="annot_dir",required=True,type=str,
                        help="transcripts annotation directory, generated by prepare_transcripts.")
    parser.add_argument("-c","--config_file",dest="config_file",required=True,
                        help="defile bam file information in this file, \
                        please refer to the example file in data folder.",type=str)
    parser.add_argument("-t","--transcript_id",dest="transcript_id",required=True,type=str,
                        help="the transcript id")
    parser.add_argument("-s","--orf_tstart",dest="orf_tstart",required=True,type=int,
                        help="transcript-level coordinates of start of ORF (orf_tstart)")
    parser.add_argument("-e","--orf_tstop",dest="orf_tstop",required=True,type=int,
                        help="transcript-level coordinates of end of ORF (orf_tstop)")
    parser.add_argument("-o","--outname",dest="outname",required=False,type=str,default="",
                        help="output file name,default is transcriptid_tstart_tstop.pdf")
    parser.add_argument('-V',"--version",action="version",version=__version__)
    args = parser.parse_args()

    args.orf_tstart = args.orf_tstart -1 # change to 0 based
    if not os.path.exists(args.annot_dir):
        raise ValueError("Error, the transcript annotation directory not found: {} \n \
                     pls run prepare_transcripts.py first. ".format(args.annot_dir))
    return args
项目:ipwb    作者:oduwsdl    | 项目源码 | 文件源码
def generateCDXJMetadata(cdxjLines=None):
    metadata = ['!context ["http://tools.ietf.org/html/rfc7089"]']
    metaVals = {
        'generator': "InterPlanetary Wayback v.{0}".format(ipwbVersion),
        'created_at': '{0}'.format(datetime.datetime.now().isoformat())
    }
    metaVals = '!meta {0}'.format(json.dumps(metaVals))
    metadata.append(metaVals)

    return metadata
项目:ipwb    作者:oduwsdl    | 项目源码 | 文件源码
def compareCurrentAndLatestIPWBVersions():
    try:
        resp = urllib2.urlopen('https://pypi.python.org/pypi/ipwb/json')
        jResp = json.loads(resp.read())
        latestVersion = jResp['info']['version']
        currentVersion = re.sub(r'\.0+', '.', ipwbVersion)
        return (currentVersion, latestVersion)
    except:
        return (None, None)
项目:song-cli    作者:ankitmathur3193    | 项目源码 | 文件源码
def main():
    """Main CLI entrypoint."""
    #print VERSION
    from commands.download import Download
    options = docopt(__doc__, version=VERSION)
    #print "You reached here"
    #print options
    print "working."
    p=Download(options)
    p.run()
项目:octogrid    作者:plotly    | 项目源码 | 文件源码
def main():
    args = docopt(__doc__, version='Octogrid {0}'.format(__version__))
    parser = ArgumentParser(args)
    parser.action()
项目:webbreaker    作者:target    | 项目源码 | 文件源码
def __init__(self, agent_json):
        self.pid = os.getpid()
        self.fqdn = socket.getfqdn()
        data = self.__read_json__(agent_json)
        try:
            self.payload = self.__formatted_elk_payload__(scan=data['fortify_build_id'], host=self.fqdn,
                                                          version=__version__,
                                                          notifiers=data['git_emails'], git_url=data['git_url'],
                                                          fortify_url=data['fortify_pv_url'])
            self.payload['start'] = datetime.now().isoformat()
            self.fortify_config = FortifyConfig()
            self.check_count = 0
            self.timeout = 15
        except (KeyError, AttributeError, UnboundLocalError) as e:
            self.log("Agent was either misconfigured or unable to initialize {0}\n".format(e))
项目:galaxy_updater    作者:danrue    | 项目源码 | 文件源码
def main():
    parser = argparse.ArgumentParser(
        description='Update ansible-galaxy requirements file')
    parser.add_argument('--inline', help="Edit requirements file in-place",
                        action='store_true')
    parser.add_argument('--yolo', help="Ignore unversioned roles",
                        action='store_true')
    parser.add_argument('--include',
                        help="Only include roles src matching pattern",
                        dest='include_pattern',
                        default=[],
                        action='append')
    parser.add_argument('--exclude',
                        help="Only include roles src matching pattern",
                        dest='exclude_pattern',
                        default=[],
                        action='append')
    parser.add_argument('--version',
                        action='version',
                        version='galaxy-updater {0}'.format(__version__))
    parser.add_argument('requirement_file', help="ansible-galaxy yaml file")
    args = parser.parse_args()

    if not os.path.isfile(args.requirement_file):
        parser.print_help()
        sys.exit(1)
    u = Updater(args.requirement_file)
    for line in u.find_latest_versions(replace_inline=args.inline,
                                       update_unversioned=not args.yolo,
                                       include_pattern=args.include_pattern,
                                       exclude_pattern=args.exclude_pattern):
        if args.yolo and "None" in line:
            continue
        print(line)
项目:sMusic-core    作者:mRokita    | 项目源码 | 文件源码
def type():
    logs.print_info("Wykonano handshake! ??czenie z serwerem zako?czone.")
    return {"request": "ok", "type": "radio", "key": config.server_key, "version": __version__}
项目:RiboCode    作者:xzt41    | 项目源码 | 文件源码
def parsing_transcript():
    parser = argparse.ArgumentParser(
        description="This script is designed for preparing transcripts annotation files."
    )
    parser.add_argument("-g","--gtf",dest="gtfFile",required=True,type=str,
                        help='Default, suitable for GENCODE and ENSEMBL GTF file, \
                              please refer: https://en.wikipedia.org/wiki/GENCODE, \
                              or using GTFupdate command to update your GTF file.')
    parser.add_argument("-f","--fasta",dest="genomeFasta",required=True,type=str,
                        help="The genome sequences file in fasta format.")
    parser.add_argument("-o","--out_dir",required=True,type=str,dest="out_dir",help="annotation directory name.")
    parser.add_argument('-V',"--version",action="version",version=__version__)
    args = parser.parse_args()

    if not os.path.exists(args.out_dir):
        try:
            os.mkdir(args.out_dir)
        except OSError as e:
            raise e

    if not os.path.exists(args.gtfFile):
        raise ValueError("Error, gtf file not found:%s.\n" % args.gtfFile)

    if not os.path.exists(args.genomeFasta):
        raise ValueError("Error, genomic fasta not found: %s\n" % args.genomeFata)

    return args
项目:quartz-browser    作者:ksharindam    | 项目源码 | 文件源码
def __init__(self): 
        global downloads_list_file
        QMainWindow.__init__(self)
        self.setWindowIcon(QIcon(":/quartz.png")) 
        self.setWindowTitle("Quartz Browser - "+__version__)
        # Window Properties
        self.history = []
        self.downloads = []
        self.confirm_before_quit = True
        # Create required directories
        for folder in [configdir, icon_dir, thumbnails_dir]:
            if not os.path.exists(folder):
                os.mkdir(folder)
        # Import and Apply Settings
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.settings = QSettings(1, 0, "quartz-browser","Quartz", self)
        self.opensettings()
        self.websettings = QWebSettings.globalSettings()
        self.websettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
        self.websettings.setMaximumPagesInCache(10)
        self.websettings.setIconDatabasePath(icon_dir)
        self.websettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, True)
        self.websettings.setAttribute(QWebSettings.JavascriptCanCloseWindows, True)
        if webkit.enable_adblock:
            self.websettings.setUserStyleSheetUrl(QUrl.fromLocalFile(program_dir + 'userContent.css'))
        # Import Downloads and Bookmarks
        self.dwnldsmodel = DownloadsModel(self.downloads, QApplication.instance())
        self.dwnldsmodel.deleteDownloadsRequested.connect(self.deleteDownloads)
        imported_downloads = importDownloads(downloads_list_file)
        for [filepath, url, totalsize, timestamp] in imported_downloads:
            try :                                                  # Check if downloads.txt is valid
                tymstamp = float(timestamp)
            except :
                self.downloads = []
                exportDownloads(downloads_list_file, [])
                print("Error in importing Downloads.")
                break
            old_download = Download(networkmanager)
            old_download.loadDownload(filepath, url, totalsize, timestamp)
            old_download.datachanged.connect(self.dwnldsmodel.datachanged)
            self.downloads.append(old_download)
        self.bookmarks = importBookmarks(configdir+"bookmarks.txt")
        self.favourites = importFavourites(configdir + 'favourites.txt')
        # Find and set icon theme name
        for theme_name in ['Adwaita', 'Gnome', 'Tango']:
            if os.path.exists('/usr/share/icons/' + theme_name):
                QIcon.setThemeName(theme_name)
                break
        self.initUI()
        self.resize(1024,714)
项目:eclcli    作者:nttcom    | 项目源码 | 文件源码
def get_base_parser(self):
        parser = argparse.ArgumentParser(
            prog='ceilometer',
            description=__doc__.strip(),
            epilog='See "ceilometer help COMMAND" '
                   'for help on a specific command.',
            add_help=False,
            formatter_class=HelpFormatter,
        )

        # Global arguments
        parser.add_argument('-h', '--help',
                            action='store_true',
                            help=argparse.SUPPRESS,
                            )

        parser.add_argument('--version',
                            action='version',
                            version=__init__.__version__)

        parser.add_argument('-d', '--debug',
                            default=bool(utils.env('MONITORINGCLIENT_DEBUG')
                                         ),
                            action='store_true',
                            help='Defaults to env[MONITORINGCLIENT_DEBUG].')

        parser.add_argument('-v', '--verbose',
                            default=False, action="store_true",
                            help="Print more verbose output.")

        parser.add_argument('--timeout',
                            default=600,
                            type=_positive_non_zero_int,
                            help='Number of seconds to wait for a response.')

        parser.add_argument('--ceilometer-url', metavar='<CEILOMETER_URL>',
                            dest='os_endpoint',
                            default=utils.env('CEILOMETER_URL'),
                            help=("DEPRECATED, use --os-endpoint instead. "
                                  "Defaults to env[CEILOMETER_URL]."))

        parser.add_argument('--ceilometer_url',
                            dest='os_endpoint',
                            help=argparse.SUPPRESS)

        parser.add_argument('--ceilometer-api-version',
                            default=utils.env(
                                'CEILOMETER_API_VERSION', default='2'),
                            help='Defaults to env[CEILOMETER_API_VERSION] '
                            'or 2.')

        parser.add_argument('--ceilometer_api_version',
                            help=argparse.SUPPRESS)

        self.auth_plugin.add_opts(parser)
        self.auth_plugin.add_common_opts(parser)

        return parser
项目:RiboCode    作者:xzt41    | 项目源码 | 文件源码
def parsing_metaplots():
    parser = argparse.ArgumentParser(
        description="""
        This script create aggregate plots of distances from the 5'end of reads to start or stop codons,
        which help determine the length range of the PRF reads that are most likely originated from the
        translating ribosomes and identify the P-site locations for each reads lengths.
        """
    )
    parser.add_argument("-a","--annot_dir",dest="annot_dir",required=True,type=str,
                        help="transcripts annotation directory, generated by prepare_transcripts.")
    parser.add_argument("-r","--rpf_mapping_file",dest="rpf_mapping_file",required=True,type=str,
                        help="ribo-seq BAM/SAM file aligned to the transcriptome.")
    parser.add_argument("-s","--stranded",dest="stranded",required=False,type=str,choices=["yes","reverse"],
                        default="yes",help="whether the data is strand-specific, \
                        reverse means reversed strand interpretation.(default: yes)")
    parser.add_argument("-m","--minimum-length",dest="minLength",required=False,type=int,default=24,
                        help="minimum length of read to output, default 24")
    parser.add_argument("-M","--maximum-length",dest="maxLength",required=False,type=int,default=36,
                        help="maximum length of read to output, default 36")
    parser.add_argument("-pv1","--pvalue1_cutoff",dest="pvalue1_cutoff",required=False,type=float,default=0.001,
                        help="pvalue cutoff of frame0 > frame2 for automatically predicting P-site location, default 0.001")
    parser.add_argument("-pv2","--pvalue2_cutoff",dest="pvalue2_cutoff",required=False,type=float,default=0.001,
                        help="pvalue cutoff of frame0 > frame2 for automatically predicting P-site location, default 0.001")
    parser.add_argument("-f0_percent","--frame0_percent",dest="frame0_percent",required=False,type=float,default=0.65,
                        help="proportion threshold of the number of reads in frame0, defined by f0/(f0+f1+f2), default 0.65")
    parser.add_argument("-o","--outname",dest="outname",required=False,type=str,default="metaplots",
                        help="name of output pdf file(default: metaplots)")
    parser.add_argument('-V',"--version",action="version",version=__version__)
    args = parser.parse_args()

    if not os.path.exists(args.annot_dir):
        raise ValueError("Error, the transcript annotation directory not found: {} \n \
                          pleas run prepare_transcripts.py first.".format(args.annot_dir))
    if args.minLength > args.maxLength:
        raise ValueError("minimum length must be <= maximum length (currently %d and %d, respectively)" % (args.minLength, args.maxLength))
    if args.minLength <= 0 or  args.maxLength <=0:
        raise ValueError("minimum length or maximum length must be larger than 0.")
    if not os.path.exists(args.rpf_mapping_file):
        raise  ValueError("Error, the rpf mapping file not found: %s\n" % args.rpf_mapping_file)
    args.stranded = True if args.stranded == "yes" else False
    args.pvalue1_cutoff = float(args.pvalue1_cutoff)
    args.pvalue2_cutoff = float(args.pvalue2_cutoff)
    args.frame0_percent = float(args.frame0_percent)

    return args
项目:RiboCode    作者:xzt41    | 项目源码 | 文件源码
def parsing_ribo():
    parser = argparse.ArgumentParser(
        description="The main function designed for detecting ORF using ribosome-profiling data."
    )
    parser.add_argument("-a","--annot_dir",dest="annot_dir",required=True,type=str,
                        help="transcripts annotation directory, generated by prepare_transcripts.")
    parser.add_argument("-c","--config_file",dest="config_file",required=True,type=str,
                        help="list bam file and P-sites information in this file, \
                        please refer to the example file in data folder.")
    # parser.add_argument("-n","--num-threads",dest="threads_num",default=1,required=False,
    #                     help="number of threads, optimal number is number of bam files.", type=int)
    parser.add_argument("-l","--longest-orf",dest="longest_orf",choices=["yes","no"],default="yes",required=False,
                        help="Default: yes, the region from most distal AUG to stop was defined as an ORF. \
                              If set to no , the position of start codon will be automatically determined by program.", type=str)
    parser.add_argument("-p","--pval-cutoff",dest="pval_cutoff",default=0.05,required=False,
                        help="P-value cutoff for ORF filtering, default 0.05", type=float)
    parser.add_argument("--stranded","--stranded",dest="stranded",required=False,type=str,choices=["yes","reverse"],
                        default="yes",help="whether the data is strand-specific, \
                        reverse means reversed strand interpretation.(default: yes)")
    parser.add_argument("-s","--start_codon",default="ATG",type=str,dest="start_codon",
                        help="The canonical start codon. default: ATG")
    parser.add_argument("-A","--alt_start_codons",default="",type=str,dest="alternative_start_codons",
                        help="The alternative start codon, such as CTG,GTG, default: None. Multiple codons should be separated by comma.")
    parser.add_argument("-S","--stop_codon",default="TAA,TAG,TGA",type=str,dest="stop_codon",
                        help="Stop codon, default: TAA,TAG,TGA")
    parser.add_argument("-t","--transl_table",default=1,dest="transl_table",type=int,
                        help="ORF translation table(Default: 1). Assign the correct genetic code based on your organism, \
                        [please refer: https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi]")
    parser.add_argument("-m","--min-AA-length",dest="min_AA_length",default="20",required=False,
                        help="The minimal length of predicted peptides,default 20", type=int)
    # parser.add_argument("-P","--parallel_num",dest="parallel_num",default=1,required=False,
    #                     help="the number of threads to read the alignment file(s), \
    #                     the optimal value is the number of alignment files, default=1",type=int)
    parser.add_argument("-o","--output-name",dest="output_name",default="final_result",required=False,
                        help="output file name, default: final_result", type=str)
    parser.add_argument("-g","--output-gtf",dest="output_gtf",action='store_true',default=False,required=False,
                        help="output the gtf file of predicted ORFs")
    parser.add_argument("-b","--output-bed",dest="output_bed",action='store_true',default=False,required=False,
                        help="output the bed file of predicted ORFs")
    parser.add_argument('-V',"--version",action="version",version=__version__)
    args = parser.parse_args()

    if not os.path.exists(args.annot_dir):
        raise  ValueError("Error, the transcript annotation directory not found: {} \n \
                     pls run prepare_transcripts.py first. ".format(args.annot_dir))

    return args
项目:RiboCode    作者:xzt41    | 项目源码 | 文件源码
def parsing_ORF_count():
    parser = argparse.ArgumentParser(
        description="This script is designed for calculating the number of reads mapping to ORF with the alignment files \
        in SAM/BAM format (aligned to genome) and a feature file in GTF format"
    )
    parser.add_argument("-s","--stranded",dest="stranded",required=False,type=str,choices=["yes","reverse"],
                        default="yes",help="whether the data is strand-specific, \
                        reverse means reversed strand interpretation. (default: yes)")
    parser.add_argument("-a","--minaqual",dest="min_quality",required=False,type=int,
                        default=10,help="skip all reads with alignment quality lower than the given minimum value (default:10)")
    parser.add_argument("-c","--count_mode",dest="count_mode",required=False,type=str,choices=["union","intersection-strict"],
                        default="intersection-strict",help="mode to handle reads overlapping more than one ORF (choices:\
                        union,intersection-strict;default: intersection-strict)")
    parser.add_argument("-g","--gtf",dest="gtf_file",required=False,type=str,default="final_result_collapsed.gtf",
                        help="ORF gtf file generated by RiboCode, default:final_result")
    parser.add_argument("-r","--rpf_mapping_file",dest="rpf_mapping_file",required=True,type=str,
                        help="ribo-seq BAM/SAM file aligned to the genome, multiple files should be separated with \",\"")
    parser.add_argument("-f","--first_exclude_codons",dest="first_exclude_codons",required=False,type=int,default=15,
                        help="excluding the reads aligned to the first few codons of the ORF, default:15")
    parser.add_argument("-l","--last_exclude_codons",dest="last_exclude_codons",required=False,type=int,default=5,
                        help="excluding the reads aligned to the last few codons of the ORF, default:5")
    parser.add_argument("-e","--exclude_min_ORF",dest="exclude_min_ORF",required=False,type=int,default=100,
                        help="the minimal length(nt) of ORF for excluding the reads aligned to first and last few codons, default:100")
    parser.add_argument("-m","--min_read",dest="min_read",required=False,type=int,default=26,
                        help="minimal read length for the counting of RPF,default:26")
    parser.add_argument("-M","--max_read",dest="max_read",required=False,type=int,default=34,
                        help="maximal read length for the counting of RPF,default:34")
    # parser.add_argument("-p","--parallel_num",dest="parallel_num",required=False,type=int,default=1,
    #                     help="the number of threads to read the alignment file(s), \
    #                     the optimal value is the number of alignment files, default=1")
    parser.add_argument("-o","--output",dest="output_file",required=False,type=str,
                        default="-",help="write out all ORF counts into a file, default is to write to standard output")
    parser.add_argument('-V',"--version",action="version",version=__version__)
    args = parser.parse_args()

    if not os.path.exists(args.gtf_file):
        raise ValueError("Error, the gtf file not found: {}".format(args.gtf_file))
    if args.first_exclude_codons * 3 + args.last_exclude_codons * 3 >= args.exclude_min_ORF:
        raise ValueError("Error, the exclude_min_ORF is too small: %i" % args.exclude_min_ORF)
    if "," in args.rpf_mapping_file:
        rpf_mapping_files = [i.strip() for i in args.rpf_mapping_file.split(",")]
        args.rpf_mapping_file = rpf_mapping_files
    else:
        args.rpf_mapping_file = [args.rpf_mapping_file]
    # if args.parallel_num > len(args.rpf_mapping_file):
    #   args.parallel_num = len(args.rpf_mapping_file)
    return args
项目:nfvbench    作者:opnfv    | 项目源码 | 文件源码
def run(self, opts, args):
        status = NFVBench.STATUS_OK
        result = None
        message = ''
        if fluent_logger:
            # take a snapshot of the current time for this new run
            # so that all subsequent logs can relate to this run
            fluent_logger.start_new_run()
        LOG.info(args)
        try:
            self.update_config(opts)
            self.setup()

            result = {
                "date": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                "nfvbench_version": __version__,
                "openstack_spec": {
                    "vswitch": self.specs.openstack.vswitch,
                    "encaps": self.specs.openstack.encaps
                },
                "config": self.config_plugin.prepare_results_config(copy.deepcopy(self.config)),
                "benchmarks": {
                    "network": {
                        "service_chain": self.chain_runner.run(),
                        "versions": self.chain_runner.get_version(),
                    }
                }
            }
            result['benchmarks']['network']['versions'].update(self.config_plugin.get_version())
        except Exception:
            status = NFVBench.STATUS_ERROR
            message = traceback.format_exc()
        except KeyboardInterrupt:
            status = NFVBench.STATUS_ERROR
            message = traceback.format_exc()
        finally:
            if self.chain_runner:
                self.chain_runner.close()

        if status == NFVBench.STATUS_OK:
            result = utils.dict_to_json_dict(result)
            return {
                'status': status,
                'result': result
            }
        return {
            'status': status,
            'error_message': message
        }