如何调用iPython noteb中用argparse编写的模块

2024-05-10 18:52:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在iPython的笔记本环境中将BioPython序列传递给Ilya Stepanov's implementation of Ukkonen's suffix tree algorithm。我在argparse组件上遇到了问题。

我以前从来没有直接和argparse打过交道。如何在不重写main()的情况下使用它?

通过,this writeup of Ukkonen's algorithm is fantastic


Tags: oftree环境ipythonargparse笔记本序列algorithm
3条回答

在Ipython笔记本中使用argparse的另一种方法是将字符串传递给:

args = parser.parse_args() (您引用的git repo的第303行。)

可能是这样的:

parser = argparse.ArgumentParser(
        description='Searching longest common substring. '
                    'Uses Ukkonen\'s suffix tree algorithm and generalized suffix tree. '
                    'Written by Ilya Stepanov (c) 2013')

parser.add_argument(
        'strings',
        metavar='STRING',
        nargs='*',
        help='String for searching',
    )

parser.add_argument(
        '-f',
        '--file',
        help='Path for input file. First line should contain number of lines to search in'
    )

以及

args = parser.parse_args("AAA --file /path/to/sequences.txt".split())

编辑:有效

我已经有了a similar problem before,,但是使用了optparse,而不是argparse

不需要更改原始脚本中的任何内容,只需将新列表分配给sys.argv,如下所示:

if __name__ == "__main__":
    from Bio import SeqIO
    path = '/path/to/sequences.txt'
    sequences = [str(record.seq) for record in  SeqIO.parse(path, 'fasta')]
    sys.argv = ['-f'] + sequences
    main()

最后我使用BioPython提取序列,然后编辑Ilya Steanov的实现来删除argparse方法。

import imp
seqs = []
lcsm = imp.load_source('lcsm', '/path/to/ukkonen.py')
for record in SeqIO.parse('/path/to/sequences.txt', 'fasta'):
    seqs.append(record)
lcsm.main(seqs)

对于算法,我让main()接受一个参数,他的strings变量,但这会向算法发送一个特殊的BioPython Sequence objects列表,re模块不喜欢这个列表。所以我必须提取序列字符串

suffix_tree.append_string(s)

suffix_tree.append_string(str(s.seq))

看起来有点脆,但这就是我现在所拥有的。

相关问题 更多 >