python子进程打印bash命令的输出[重复]

fv2wmkja  于 2023-02-18  发布在  Python
关注(0)|答案(1)|浏览(143)
    • 此问题在此处已有答案**:

"OSError: [Errno 2] No such file or directory" while using python subprocess with command and arguments(3个答案)
4小时前关门了。
我正在尝试使用python输出tree命令的结果

import subprocess

cmd = "tree /home/ubuntu/data"

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

print(returned_output)

得到的是

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'
>>>

我期待

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

2 directories, 2 files

我怎样才能做到这一点。

omqzjyyz

omqzjyyz1#

您可能想尝试shell=True,如下所示:

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

另请在www.example.com上阅读有关shell=True用法的https://docs.python.org/3/library/subprocess.html#

相关问题