如何通过命令行为 python 脚本的函数提供参数?
目前,这是我的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的file和len_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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 argparse 模块 来实现这一点。
从文档来看,
如果您使用的 python 版本早于 2.7,则应该使用 optparse模块,实现类似的效果。
You could use the argparse module for that.
From the docs,
If you are using a version of python earlier than 2.7, you should use the optparse module, to achieve a similar effect.
sys.argv
是参数列表,第一个元素是脚本名称。它是一个字符串列表,因此如果任何参数是数字,则必须使用int()
或float()
对其进行转换。因此,如果您像这样调用脚本:
sys.argv
将是这样的:在您的情况下,您可以使脚本如下:
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 usingint()
orfloat()
.So, if you called a script like so:
sys.argv
would be this:In your case, you could make your script this:
我推荐
argparse
和一个名为 的漂亮包装器plac
。在您的情况下,您需要做的就是:...并且 plac 将处理所有事情,因为它能够从您的签名中找出要使用的命令行参数功能。非常酷,请查看文档了解更多信息(它可以做更多事情)。
I'd recommend
argparse
and a nice wrapper for it calledplac
. In your case all you'd need to do is:...and
plac
will 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).参考一下这个就可以了。
http://www.dalkescientific.com/writings/NBN/python_intro/command_line.html
Just refer to this.
http://www.dalkescientific.com/writings/NBN/python_intro/command_line.html