【问题标题】:argparse write results into a fileargparse 将结果写入文件
【发布时间】:2018-07-24 16:24:21
【问题描述】:

我正在尝试学习如何使用 argparse() 将 .py 代码转换为命令行。下面是我的测试学习脚本。我不知道如何将输出写入文件。我尝试了两种情况:

  1. 我使用parser.add_argument('out_file', type= argparse.FileType('w')),它给出了以下错误:“强制转换为 Unicode:需要字符串或缓冲区,找到文件”。我的理解是已经打开了一个文件进行写入。
  2. 或者我使用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


    【解决方案1】:

    下次发布完整的堆栈,特别是错误发生的位置 - 这将立即显示错误的位置,可能是什么。我猜这里:

    #in_file = open(in_file, "r")
    

    输出文件也一样:

    out_file = open(out_file, "r")
    

    type= argparse.FileType 的工作方式是为您打开文件。您正在尝试打开一个打开的文件 - 删除这两行,并直接使用 args.in_fileargs.out_file 作为文件描述符。

    使用FileType 而不是您自己打开的字符串的优点是argparse 将检查打开时的错误,并在打开文件时以精美的打印方式通知您。

    【讨论】:

      【解决方案2】:

      您已将in_fileout_file 的类型设置为“文件对象”。将其设置为str,并将命令行中的文件名作为相关参数传递到文件的路径。

      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 that enables to visualize GOs")
          parser.add_argument('in_file', type=str, required= True)   # Enter the file path here
          parser.add_argument('out_file', type=str, required= True)  # Enter the file path here
          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")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-18
        • 2013-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-29
        相关资源
        最近更新 更多