使用argparse创建输出文件

问题描述 投票:4回答:3

我一直在我正在编写的程序中使用argparse但是它似乎没有创建声明的输出文件。

我的代码是:

parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")
with open(output, 'w') as output_file:
            output_file.write("%s\n" % item)

我也尝试过:

parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
    output_file.write("%s\n" % item)

发生的错误是:

    output_file.write("%s\n" % item)
NameError: name 'output_file' is not defined

有人可以解释为什么我发生这个错误以及如何解决它?

我的所有代码:

from __future__ import print_function
from collections import defaultdict
from itertools import groupby
import argparse #imports the argparse module so it can be used
from itertools import izip
#print = print_function




parser = argparse.ArgumentParser() #simplifys the wording of using argparse as stated in the python tutorial
parser.add_argument("-r1", type=str, action='store',  dest='input1', help="input the forward read file") # allows input of the forward read
parser.add_argument("-r2", type=str, action='store', dest='input2', help="input the reverse read file") # allows input of the reverse read
parser.add_argument("-v", "--verbose", action="store_true", help=" Increases the output, only needs to be used to provide feedback to Tom for debugging")
parser.add_argument("-n", action="count", default=0, help="Allows for up to 5 mismatches, however this will reduce accuracy of matching and cause mismatches. Default is 0")
#parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
parser.add_argument("-fastq", action="store_true", help=" States your input as fastq format")
parser.add_argument("-fasta", action="store_true", help=" States your input as fasta format")
parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")


args = parser.parse_args()
def class_chars(chrs):
    if 'N' in chrs:
        return 'unknown'
    elif chrs[0] == chrs[1]:
        return 'match'
    else:
        return 'not_match'

with open(output, 'w') as output_file:



    s1 = 'aaaaaaaaaaN123bbbbbbbbbbQccc'
    s2 = 'aaaaaaaaaaN456bbbbbbbbbbPccc'
    n = 0
    consec_matches = []
    chars = defaultdict(int)

    for k, group in groupby(zip(s1, s2), class_chars):
        elems = len(list(group))
        chars[k] += elems
        if k == 'match':
            consec_matches.append((n, n+elems-1))
        n += elems

    print (chars)
    print (consec_matches)
    print ([x for x in consec_matches if x[1]-x[0] >= 9])
    list = [x for x in consec_matches if x[1]-x[0] >= 9]
    flatten_list= [x for y in list for x in y]
    print (flatten_list)
    matching=[y[1] for y in list for x in y if x ==0 ]
    print (matching)
    magic = lambda matching: int(''.join(str(i) for i in matching)) # Generator exp.
    print (magic(matching))
    s2_l = s2[magic(matching):]
    line3=s1+s2_l
    print (line3)
    if line3:
        output_file.write("%s\n" % item)
python python-2.7 output argparse
3个回答
4
投票

您缺少实际解析参数的位:

parser.add_argument("-o", "--output", help="Directs the output to a name of your choice")
args = parser.parse_args()
with open(args.output, 'w') as output_file:
    output_file.write("%s\n" % item)

parser.parse_args()将为您提供一个对象,您可以使用长选项名称栏来破解,从而可以通过名称访问参数。


1
投票

当我运行你的脚本时,我得到:

Traceback (most recent call last):
  File "stack23566970.py", line 31, in <module>
    with open(output, 'w') as output_file:
NameError: name 'output' is not defined

您的脚本中没有地方可以执行output = ...

我们可以用以下方法纠正:

with open(args.output, 'w') as output_file:

argparse返回值作为args对象的属性。

现在我得到:

Traceback (most recent call last):
  File "stack23566970.py", line 62, in <module>
    output_file.write("%s\n" % item)
NameError: name 'item' is not defined

再说一遍,没有item = ...线。

什么是item应该是什么?


0
投票

我认为你几乎得到了最正确的答案。唯一的问题是没有从args中读取output_file

parser.add_argument("-o", "--output", action='store', 
                    type=argparse.FileType('w'), dest='output',
                    help="Directs the output to a name of your choice")
#output_file is not defined, you want to read args.output to get the output_file
output_file = args.output
#now you can write to it
output_file.write("%s\n" % item)
© www.soinside.com 2019 - 2024. All rights reserved.