0

I am trying to run the shell command "history" from python (not reading from ~/.bash_history) and read it's output to a variable. A small twist is that I am using awk to parse only the timestamps of the commands from which I make a list of timestamps. I then compare the max(timestamp) and the timestamp[end_index] to check if they are equal.

import time
from datetime import datetime
from subprocess import Popen, PIPE, STDOUT

# Check HISTTIMEFORMAT env variable for history timestamp format
check_hist_format = Popen("echo $HISTTIMEFORMAT", shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
hist_var = check_hist_format.communicate()[0].decode()

if hist_var == "\n":
    os.environ["HISTTIMEFORMAT"] = "20%y/%m/%d %T "

# Run "history" command and retrive its timestamps
script = Popen("bash -i -c  'history -r;history' | awk \'{print $2}\' ", shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
last_cmd = list(script.communicate())[0].decode().split('\n')

last_cmd_timestamp = []
for i in last_cmd:
    try:
        last_cmd_timestamp.append(datetime.strptime(str(i), '%Y/%m/%d').timestamp())
    except:
        #print("Exception")
        pass

# Get the biggest timestamp
big_timestamp = (max(last_cmd_timestamp))
# Get the latest timestamp
last_timestamp = (last_cmd_timestamp[len(last_cmd_timestamp)-1])

# If they are the same, then print "Success"
if big_timestamp == last_timestamp:
    print("Success")
else:
    print("Failed")

It runs correctly and output "Success" when I run with the command python3 test.py. However, when I run using the command python3 test.py &, it does not output anything no matter how long I wait. Is it possible to please explain my why this happens and lead me in the right direction to find a fix?

The above history script was obtained from Invoking history command on terminal via Python script

  • 1
    It appears that, because you specify `-i` to make it an interactive shell, bash will not proceed unless it can connect to the terminal. It stops at the `bash` command. I assume you have noticed that as soon as you type `fg` to bring the command to the terminal, it runs to completion. Even setting `stdin=DEVNULL` did not let it proceed. – Tim Roberts Jul 06 '21 at 02:42
  • This is right. After I typed fg, it worked as expected. Is there anyway to automate that from within the python code? – Premkumar Vincent Jul 06 '21 at 05:01
  • I tried to do "bash -i -c 'history -r;history' | awk \'{print $2}\' & fg" to force that commandline to run in the foreground. However, I ended up with "/bin/sh: line 0: fg: no job control" warning error instead – Premkumar Vincent Jul 06 '21 at 05:45
  • That's not going to help. I'm not convinced that this is possible. I'm also not convinced this is useful. What are you actually trying to do here? – Tim Roberts Jul 06 '21 at 06:07
  • I am trying to read up-to-date command history into a variable. This can help me get a list of timestamps since "awk '{print $2}' cuts only the timestamp section from "history" command. I understand that I can read ~/.bash_history file directly. However, I still need to run history -a in order to update ~/.bash_history without logging out. If I had to rephrase the question, it would be: 1) Update _~/.bash_history_ file using python code 2) Read _~/.bash_history_ file and parse the timestamps (2) is easy to do but I'm stuck with (1) – Premkumar Vincent Jul 06 '21 at 06:23
  • _I'm stuck with (1) _ ... `.bash_history` is just a simple text file. I don't understand why you want to manipulate it, but it's not different to updating any other text file. – user1934428 Jul 06 '21 at 06:34
  • My appologies, I should have made it clearer in the previous comment. In order to update ~/.bash_history file (in the sense, all the up-to-date commands are written to it) without exiting the current bash session, I need to run _"history -a"_ command (if there is an alternative, it would be highly appreciated). My trouble is not file manipulation, but rather executing _"history -a"_ command from python (python is started as a background process) – Premkumar Vincent Jul 06 '21 at 06:55

0 Answers0