2

I have to print bash history using subprocess package.

import subprocess co = subprocess.Popen(['history'], stdout = subprocess.PIPE) History = co.stdout.read() print("----------History----------" + "\n" + History) 

but they prompt an error

 Traceback (most recent call last): File "test.py", line 4, in <module> co = subprocess.Popen(['history'], stdout = subprocess.PIPE) File "/usr/lib/python2.7/subprocess.py", line 394, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1047, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory 
3

2 Answers 2

2

Normally, you would need to add shell=True argument to your Popen call:

co = subprocess.Popen(['history'], shell=True, stdout = subprocess.PIPE) 

Or to manually specify the shell you want to call.

co = subprocess.Popen(['/bin/bash', '-c', 'history'], stdout = subprocess.PIPE) 

Unfortunately, in this particular case it won't help, because bash has empty history when used non-interactively.

A working solution would be to read ${HOME}/.bash_history manually.

Sign up to request clarification or add additional context in comments.

Comments

0

Kit is correct, reading ~/.bash_history may be a better option:

from os.path import join, expanduser with open(join(expanduser('~'), '.bash_history'), 'r') as f: for line in f: print(line) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.