0

I am trying to output the result of tree command using python

import subprocess

cmd = "tree /home/ubuntu/data"

# returns output as byte string
returned_output = subprocess.check_output(cmd)

print(returned_output)

what is get is

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.10/subprocess.py", line 420, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/usr/lib/python3.10/subprocess.py", line 501, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.10/subprocess.py", line 969, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.10/subprocess.py", line 1845, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'tree /home/ubuntu/data'
>>> 

I am expecting

/home/ubuntu/data
├── input
│   └── test.txt
└── output
    └── test.txt

2 directories, 2 files

How can i achieve this.

Santhosh
  • 9,965
  • 20
  • 103
  • 243

1 Answers1

0

You may want to try shell=True like below:

returned_output = subprocess.check_output(cmd, shell=True)

Also read about the usage of shell=True at https://docs.python.org/3/library/subprocess.html#

SH47
  • 11
  • 3