亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

python2.7 - 怎樣才能讓python 腳本像shell命令一樣直接運行并可以接收參數(shù)?
天蓬老師
天蓬老師 2017-04-17 17:39:57
0
3
546

如果您的答案是:給py腳本運行權(quán)限,并且加上 #!/usr/bin/env python 的話,請您繼續(xù)往下看。

今天在PyPI上發(fā)現(xiàn)一個包pyfasta,pip安裝之后,可以在命令行下輸入pyfasta直接運行

root$ pyfasta extract --help
Usage: extract some sequences from a fasta file. e.g.:
               pyfasta extract --fasta some.fasta --header at2g26540 at3g45640

Options:
  -h, --help     show this help message and exit
  --fasta=FASTA  path to the fasta file

安裝包內(nèi)只有四個py文件( __init__.py, fasta.py, records.py, split_fasta.py)

  1. 這是怎么做到的?

  2. pyfasata 可以指定不同的action(下述的四個),接受不同的參數(shù),從而實現(xiàn)不同的功能
    這樣要怎么做?

可以結(jié)合 __init__.py 的內(nèi)容,我有點頭緒,但又不是完全懂,已付__init__.py的代碼
`

root$pyfasta 
available actions:
    `extract`: extract sequences from a fasta file
    `info`: show info about the fasta file and exit.
    `split`: split a large fasta file into separate files
             and/or into K-mers.
    `flatten`: flatten a fasta file inplace so that later`

import sys
from .fasta import Fasta, complement, DuplicateHeaderException
from .records import *
from .split_fasta import split
import optparse

def main():
    help = """
    available actions:
        `extract`: extract sequences from a fasta file
        `info`: show info about the fasta file and exit.
        `split`: split a large fasta file into separate files
                 and/or into K-mers.
        `flatten`: flatten a fasta file inplace so that later
                   command-line (and programmattic) access via
                   pyfasta will use the inplace flattened version
                   rather than creating another .flat copy of the
                   sequence.

    to view the help for a particular action, use:
        pyfasta [action] --help
    e.g.:
        pyfasta extract --help
    """
    if len(sys.argv) == 1:
        print(help)
        sys.exit()

    action = sys.argv[1]

    sglobals = globals()
    if not action in sglobals:
        print("%s not a valid action" % action)
        print(help)
        sys.exit()

    globals()[action](sys.argv[2:])

def info(args):
    """
    >>> info(['tests/data/three_chrs.fasta'])
    <BLANKLINE>
    tests/data/three_chrs.fasta
    ===========================
    >chr3 length:3600
    >chr2 length:80
    >chr1 length:80
    <BLANKLINE>
    3760 basepairs in 3 sequences
    """
    parser = optparse.OptionParser("""\
   print headers and lengths of the given fasta file in order of length. e.g.:
        pyfasta info --gc some.fasta""")

    parser.add_option("-n", "--n", type="int", dest="nseqs",
                      help="max number of records to print. use -1 for all",
                      default=20)
    parser.add_option("--gc", dest="gc", help="show gc content",
                      action="store_true", default=False)
    options, fastas = parser.parse_args(args)
    if not (fastas):
        sys.exit(parser.print_help())
    import operator

    for fasta in fastas:
        f = Fasta(fasta)
        info = [(k, len(seq)) for k, seq in f.items()]

        total_len = sum(l for k, l in info)
        nseqs = len(f)
        if options.nseqs > -1:
            info = sorted(info,  key=operator.itemgetter(1, 0), reverse=True)
            info = info[:options.nseqs]
        else:
            info.sort()

        print("\n" + fasta)
        print("=" * len(fasta))
        for k, l in info:
            gc = ""
            if options.gc:
                seq = str(f[k]).upper()
                g = seq.count('G')
                c = seq.count('C')
                gc = 100.0 * (g + c) / float(l)
                gc = "gc:%.2f%%" % gc
            print((">%s length:%i" % (k, l)) + gc)

        if total_len > 1000000:
            total_len = "%.3fM" % (total_len / 1000000.)
        print()
        print("%s basepairs in %i sequences" % (total_len, nseqs))

def flatten(args):
    """
    >>> flatten(['tests/data/three_chrs.fasta'])
    """
    parser = optparse.OptionParser("""flatten a fasta file *inplace* so all later access by pyfasta will use that flattend (but still viable) fasta file""")
    _, fasta = parser.parse_args(args)
    for fa in fasta:
        f = Fasta(fa, flatten_inplace=True)

def extract(args):
    """
    >>> extract(['--fasta', 'tests/data/three_chrs.fasta', 'chr2'])
    TAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAT
    """

    parser = optparse.OptionParser("""extract some sequences from a fasta file. e.g.:
               pyfasta extract --fasta some.fasta --header at2g26540 at3g45640""")
    parser.add_option("--fasta", dest="fasta", help="path to the fasta file")
    parser.add_option("--header", dest="header", help="include headers", action="store_true", default=False)
    parser.add_option("--exclude", dest="exclude", help="extract all sequences EXCEPT those listed", action="store_true", default=False)
    parser.add_option("--file", dest="file", help=\
                      "if this flag is used, the sequences to extract" \
                      " are read from the file specified in args"
                      , action="store_true", default=False)
    parser.add_option("--space", dest="space", action="store_true", help=\
                      "use the fasta identifier only up to the space as the key",
                      default=False)
    options, seqs = parser.parse_args(args)
    if not (options.fasta and len(seqs)):
        sys.exit(parser.print_help())

    key_fn = (lambda k: k.split()[0]) if options.space else None
    f = Fasta(options.fasta, key_fn=key_fn)
    if options.file:
        seqs = (x.strip() for x in open(seqs[0]))
    if options.exclude:
        seqs = sorted(frozenset(iter(f.keys())).difference(seqs))

    for seqname in seqs:
        seq = f[seqname]
        if options.header:
            print(">%s" % seqname)
        print(seq)


if __name__ == "__main__":
    main()
天蓬老師
天蓬老師

歡迎選擇我的課程,讓我們一起見證您的進(jìn)步~~

reply all(3)
Ty80

Achieved using sys.argv

伊謝爾倫

I know, the package that comes with python, optparse, is what is used above.
The new version now implemented is argparse,
There are also third-party packages Clint, Click, docopt, Plac, Cliff
The above-mentioned third-party packages should be They are all easier to use than the ones that come with them (there are too many codes to write with the ones that come with them)
You can take a look at this comparative article Comparison of Python command line parsing libraries - Argparse, Docopt, and Click

Clint
clint is a Python module which is filled with very useful tools for developing command-line applications. It supports features such as; CLI colors and indents, simple and powerful column printer, iterator based progress bars and implicit argument handling.

Click
click is an upcoming Python package for creating command-line interfaces in a composable way with as little code as possible. This “Command-line Interface Creation Kit” is highly configurable but comes with good defaults out of the box.

docopt
docopt is a lightweight, highly Pythonic package that allows creating command-line interfaces easily and intuitively, by parsing POSIX-style usage instructions.

Plac
Plac is a simple wrapper over the Python standard library argparse, which hides most of its complexity by using a declarative interface: the argument parser is inferred rather than written down by imperatively. This module targets especially unsophisticated users, programmers, sys-admins, scientists and in general people writing throw-away scripts for themselves, who choose to create a command-line interface because it is quick and simple.

Cliff
Cliff is a framework for building command-line programs. It uses setuptools entry points to provide subcommands, output formatters, and other extensions. The framework is meant to be used to create multi-level commands such as subversion and git, where the main program handles some basic argument parsing and then invokes a sub-command to do the work.

Among the third-party packages, Click and docopt should be better. Others are currently unknown.
For detailed information, please refer to Command-line Applications here.
As for the script hello.py, how to run hello? It is recommended that you take a look at python's setuptools
or see this article on how to run python commands like ls -l

小葫蘆

1. How is this done?
The Python command line itself supports adding parameters. All parameters on the command line (including the py file name itself) can be obtained using sys.argv.

# hello.py
import sys

print sys.argv

Then we execute python hello.py hello on the command line and the output is:

['hello.py', 'hello']

Of course you may have discovered that its command line does not start with python. This is because (estimated) the package added a custom command during the installation process. Manual method: ( Ubuntu-14.04 Verification is valid) Enter alias pyhello="python /path/hello.py" in the command line, thus adding pyhello Such a command, entering it is equivalent to executing python /path/hello.py. python開頭的,這是因為(估計)是該包在安裝過程中,增加了一條自定義的命令,手動方法:(Ubuntu-14.04驗證有效)在命令行中輸入alias pyhello="python /path/hello.py",這樣就在系統(tǒng)中增加了pyhello這么一個命令,輸入它就相當(dāng)于執(zhí)行python /path/hello.py。

2.……怎么做?

嗯,上述原理已經(jīng)知道了,你在你的程序里判斷一下參數(shù),不就OK了?別說4個,40個都沒問題……

3.Extra

如果要活用命令行的話,Python有個標(biāo)準(zhǔn)包叫getopt

2.…How to do it? ???? ??Well, you already know the above principles. Just judge the parameters in your program. Isn't it OK? Don’t say 4, 40 is fine...?? ????3.Extra???? ??If you want to make full use of the command line, Python has a standard package called getopt that is very useful. ??Good luck to you. ??
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template