【发布时间】:2018-07-24 16:24:21
【问题描述】:
我正在尝试学习如何使用 argparse() 将 .py 代码转换为命令行。下面是我的测试学习脚本。我不知道如何将输出写入文件。我尝试了两种情况:
- 我使用
parser.add_argument('out_file', type= argparse.FileType('w')),它给出了以下错误:“强制转换为 Unicode:需要字符串或缓冲区,找到文件”。我的理解是已经打开了一个文件进行写入。 - 或者我使用
in_file = open(in_file, "r"),并得到AttributeError: 'str' object has no attribute 'write',这意味着它将我对out_file 变量的输入视为字符串,而不是作为应该写入结果的文件。
如果能帮助您解决这些问题,我将不胜感激。
import csv
import argparse
import numpy as np
def TESTFun(x_center, y_center, in_file, out_file):
#in_file = open(in_file, "r")
out_file = open(out_file, "w")
f= np.genfromtxt(("\t".join(i) for i in csv.reader(in_file)),
delimiter = "\t",
dtype = int)
summ = x_center + y_center + f
return out_file.write(str(summ) + "\n")
out_file.close()
def ToCommandLine():
parser = argparse.ArgumentParser(description="This is a command to test")
parser.add_argument('in_file', type= argparse.FileType('r')) #nargs='?'
parser.add_argument('out_file', type= argparse.FileType('w'))
parser.add_argument('-x_center', type= float, required= True)
parser.add_argument('-y_center', type= float, required= True)
args = parser.parse_args()
TESTFun(args.x_center, args.y_center, args.in_file, args.out_file)
if __name__ == '__main__':
ToCommandLine()
TESTFun(1, 4, "test.txt", "outtest.txt")
【问题讨论】:
标签: python command-line argparse