3

I have a script that asks the user for the path to their desired directory

default_path =  '/path/to/desired/directory/'

user_path = raw_input("Enter new directory [{0}]: ".format(default_path)) or default_path

print user_path

The script has a "default" directory if no input is given. I want the script to "remember" the directory entered by the user. That is, the next time the script is run I want the default path to be the path input by the last user. Is this possible?

Maybe more generally, is there a good reference for writing command-line tools in python?

  • 2
    re: your general question. I wish there was. I like python as a language, but most CLI tools written in python are horrible. Most that I've used (including but not limited to the various openstack CLI tools like glance or nova-manage) have awful option processing and, worse, make no effort to produce output that can easily be re-used in other programs (like awk or sed) - it's like many/most python devs have no idea that unix tools are supposed to work WITH other tools and write them as if they're writing a windows CLI tool. This is not a problem with the language, it's a cultural problem. – cas May 11 '16 at 1:15
  • @cas, yes indeed. Would you know of a "shell-think by example for Python developers" ? – denis Jan 2 '17 at 12:12
5

If you are maintaining the program, then make it store the history. In Python, use the readline library and make it store a history file.

If you don't want to modify the program, you can use a wrapper such as rlwrap.

rlwrap -H ~/.myprogram.history myprogram
3

For this sort of thing, you want to use a configuration file of some sort. Usually a dotfile in the user's home directory will suffice for this sort of thing.

3

You should store your information in a file, for which the location adheres to the XDG Base Directory Specification.

As your material is data and not config you should try if the environment variable XDG_DATA_HOME exists and create a file or a utility specific subdirectory under that, where you store the file. If that environment variable does not exists, default to ~/.local/share:

base_dir = os.environ.get('XDG_DATA_HOME', 
                  os.path.join(os.environ['HOME'], '.local', 'share'))
util_data_dir = os.path.join(base_dir, util_name)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.