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
Shubham Gupta
  • 43
  • 1
  • 4
  • 1
    add `shell=True` in the Popen call [relevant question](https://stackoverflow.com/questions/9935151/popen-error-errno-2-no-such-file-or-directory) – Avishay Cohen Nov 28 '18 at 11:27
  • 3
    Possible duplicate of [Popen error: \[Errno 2\] No such file or directory](https://stackoverflow.com/questions/9935151/popen-error-errno-2-no-such-file-or-directory) – Avishay Cohen Nov 28 '18 at 11:28
  • You also want to avoid raw `Popen` as recommended in its documentation. See perhaps further https://stackoverflow.com/a/51950538/874188 – tripleee Nov 28 '18 at 11:49

2 Answers2

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.

Kit.
  • 2,386
  • 1
  • 12
  • 14
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)
cody
  • 11,045
  • 3
  • 21
  • 36