如何通过命令行为 python 脚本的函数提供参数?

发布于 2024-11-06 08:12:04 字数 855 浏览 1 评论 0原文

目前,这是我的Python脚本(TagGen),它有一个功能:

def SJtag(file,len_tag):

    import csv
    reader = csv.reader(open(file), dialect='excel-tab' )
    for row in reader:
        qstarts = row[1].split(",")[1:-1] 
        n = len_tag/2
        for i in qstarts:  
            name = row[0]

            start = int(i)-n
            if start<0:
                start = 0      

            end = int(i)+n
            if end>len(row[2]):
                end=len(row[2])

            tag = row[2][start:end]    
            print name, i, tag, len(tag)

SJtag("QstartRefseqhg19.head",80)

我想给出SJtag的filelen_tag参数 使用 bash 命令行的函数,如下所示:

python ./TagGen QstartRefseqhg19.head 80

我该如何做到这一点,或类似的事情?

感谢您的帮助!

Currently this is my python script (TagGen) which has one function:

def SJtag(file,len_tag):

    import csv
    reader = csv.reader(open(file), dialect='excel-tab' )
    for row in reader:
        qstarts = row[1].split(",")[1:-1] 
        n = len_tag/2
        for i in qstarts:  
            name = row[0]

            start = int(i)-n
            if start<0:
                start = 0      

            end = int(i)+n
            if end>len(row[2]):
                end=len(row[2])

            tag = row[2][start:end]    
            print name, i, tag, len(tag)

SJtag("QstartRefseqhg19.head",80)

I want to give the file and len_tag parameters of the SJtag function using bash comand line, something like this:

python ./TagGen QstartRefseqhg19.head 80

How can I do this, or some thing similar?

Thanks for your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

坏尐絯 2024-11-13 08:12:04

您可以使用 argparse 模块 来实现这一点。

从文档来看,

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
           help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
           const=sum, default=max,
           help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

如果您使用的 python 版本早于 2.7,则应该使用 optparse模块,实现类似的效果。

You could use the argparse module for that.

From the docs,

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
           help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
           const=sum, default=max,
           help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

If you are using a version of python earlier than 2.7, you should use the optparse module, to achieve a similar effect.

水波映月 2024-11-13 08:12:04

sys.argv 是参数列表,第一个元素是脚本名称。它是一个字符串列表,因此如果任何参数是数字,则必须使用 int()float() 对其进行转换。

因此,如果您像这样调用脚本:

$ python myscript.py 1 foo bar baz

sys.argv 将是这样的:

["myscript.py", "1", "foo", "bar", "baz"]

在您的情况下,您可以使脚本如下:

import sys
import csv

def SJtag(file,len_tag):
    reader = csv.reader(open(file), dialect='excel-tab' )
    for row in reader:
        qstarts = row[1].split(",")[1:-1] 
        n = len_tag/2
        for i in qstarts:  
            name = row[0]

            start = int(i)-n
            if start<0:
                start = 0      

            end = int(i)+n
            if end>len(row[2]):
                end=len(row[2])

            tag = row[2][start:end]    
            print name, i, tag, len(tag)

if __name__ == '__main__':
    SJtag(sys.argv[1], int(sys.argv[2]))

sys.argv is the arguments list, with the first element being the script name. It's a list of strings, so if any of the parameters are numbers, you'll have to convert them using int() or float().

So, if you called a script like so:

$ python myscript.py 1 foo bar baz

sys.argv would be this:

["myscript.py", "1", "foo", "bar", "baz"]

In your case, you could make your script this:

import sys
import csv

def SJtag(file,len_tag):
    reader = csv.reader(open(file), dialect='excel-tab' )
    for row in reader:
        qstarts = row[1].split(",")[1:-1] 
        n = len_tag/2
        for i in qstarts:  
            name = row[0]

            start = int(i)-n
            if start<0:
                start = 0      

            end = int(i)+n
            if end>len(row[2]):
                end=len(row[2])

            tag = row[2][start:end]    
            print name, i, tag, len(tag)

if __name__ == '__main__':
    SJtag(sys.argv[1], int(sys.argv[2]))
╰◇生如夏花灿烂 2024-11-13 08:12:04

我推荐 argparse 和一个名为 的漂亮包装器plac。在您的情况下,您需要做的就是:

if __name__ == '__main__':
    import plac; plac.call(SJtag)

...并且 plac 将处理所有事情,因为它能够从您的签名中找出要使用的命令行参数功能。非常酷,请查看文档了解更多信息(它可以做更多事情)。

I'd recommend argparse and a nice wrapper for it called plac. In your case all you'd need to do is:

if __name__ == '__main__':
    import plac; plac.call(SJtag)

...and placwill handle everything, as it is able to figure out the command-line arguments to use from the signature of your function. Very cool, check out the docs for more (it can do a lot more).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文