简体   繁体   中英

Force Python to update command history file from command line?

I use Python without a GUI/IDE by issuing Python from the Bash command line. I use it within a Cygwin environment, which behaves like a Linux system in many respects.

The file used for the history of commands issued at the Python command line is stored in ~/.python_history . I can easily scoot in and yank content for manipulation using vim's Buffer Explorer . It's also easy to yank manipulated content into the system clipboard for pasting at the Python command line. (For more tactical revisions of commands, on the other hand, I just use readline to vim previous commands and a single-line basis.)

I have found that ~/.python_history doesn't update after each command. I'm not sure how often it is updated, but it's clear that exiting Python causes it to update. Putting into the background with Ctrl+Z does not.

Is there a quick and convenient way from the Python command line to force an update to ~/.python_history ?

Reading through this module , I found out readline.write_history_file(path) may be what you are searching for:

Save the history list to a readline history file, overwriting any existing file. The default filename is ~/.history First thing in the interactive interpreter, do

import readline.write_history_file as whf # write history file

Then you can do whf() or whf("path/to/.historyfile") , and your python history gets saved to disk immediately.

EDIT:

I'm not sure how often it is updated

It is only updated when you exit the interpreter. If you kill it, the history won't get saved, and Ctrl+Z just causes the interpreter to be suspended. If you then unsuspend it (by executing fg or bg , for example) and exit it normally, the history file will get written.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM