1

I have made a python script that asks the user to enter 2 or 3 filenames, which should be analysed. The filename insertion is done in the script (it is not passed as argument to argparse, because there are other choices that user has to make before that). Due to the company naming convention these filenames can be quite long and thus cumbersome to type. To help the user I am printing the contents of directory. For now I am using something like this:

fname = raw_input("Insert phase 1 filename: ")

(than I check the if file exists etc...)

Is there a way to implement autocomplete for filenames inside the python script by writing custom input() function?

Note that the script must run on different machines / OS and I can not ask users to install some non-standard python libraries.

If there is no clean way to do it I might use less fancy solution of just printing a number before the filenames in the directory and than ask the user to insert just the number.

FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
  • 3
    Whilst this may be possible, there is no simple way to do this with `raw_input2. In general, it is not great practise to use `raw_input` for anything other than learning. You say that you can't use command line options, but are you completely sure that is the case? – FHTMitchell Jul 26 '18 at 16:28
  • Thank you. Solution from duplicate works on my home machine (Ubuntu). I will test it tomorrow at work on other machines. – NonStandardModel Jul 26 '18 at 16:58
  • @FTHMitchell The edited python-2.x tag is not exactly correct, because I check in the beginning of script the python version and set raw_input = input if python-3.x – NonStandardModel Jul 26 '18 at 17:02
  • 1
    Ah ok, well you can edit it back. I would go the other way and try and keep things modern so do `if sys.version_info >= (3,): input = raw_input` instead – FHTMitchell Jul 26 '18 at 17:03

1 Answers1

2

This might help: Tab completion in Python's raw_input()

If you don't want to use that and just "guess" the file:

commands = ["cute_file", "awesome_file"]

def find_file(text):
    options = [i for i in commands if i.startswith(text)]
    if len(options):
        return options
    else:
        return None


my_input = input("File name:")
print(find_file(my_input))
Adelina
  • 10,915
  • 1
  • 38
  • 46