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