2

I'm using Click to pass in an argument that is a file name. This file name is meant to be used by ConfigParser.SafeConfigParser.read() to read an ini file. Unfortunately, Click passes in a file object which read() cannot handle.

Is there a way to allow read() to take a file object or can Click be configured to not open the file (but still do the checks)?

orange
  • 7,755
  • 14
  • 75
  • 139

1 Answers1

1

Note: I found out that ConfigParser has a method for reading file handles specifically. It is called readfp(self, fp, filename=None). This if probably a better answer. I'll leave my old answer below, if someone should be interested in that solution.

You can get the filename from the filehandle using the name property. This can be passed to ConfigParser.SafeConfigParser.read().

Small example just printing out the filename:

import click

@click.command()
@click.argument('filehandle', type=click.File('rb'))
def print_filename(filehandle):
    print "File name: %s" % filehandle.name

if __name__=="__main__":
    print_filename()
J. P. Petersen
  • 4,871
  • 4
  • 33
  • 33
  • I was hoping for a solution for which the file doesn't need to be opened twice. – orange Feb 16 '17 at 02:00
  • I just saw that `ConfigParser` has a method for reading file handles specifically. It is called `readfp(self, fp, filename=None)`. It does not open the file, so it should work. – J. P. Petersen Feb 16 '17 at 08:51