Capture result of bash script into a Python progra

2019-07-22 19:47发布

问题:

I am interested in use a list of directories created in a bash script under the name list_of_dirs_in_bash and pass it to a list in my Python general program.

So, after doing in my Python script:

subprocess.call("my_bash_script.sh")

do something like:

list_of_dirs_in_python = list_of_dirs_in_bash

and then I can work with that list in Python. Sure it is not difficult but everything I have found is the other way around (from Python to bash). Thanks.

回答1:

[Python 3.Docs]: subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None) is what you need (simplest variant) for this task, as it will return the process' stdout.
From there, decode and split the return value (string) to get individual lines.

Example (did everything from command line):

[cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow]> ls
a.py        q049058700  q049654022  q051914879  q052090348  q053230645  q053781370  q054269984  q055357490  q056055568
q038171543  q049499683  q051073129  q052051111  q052720961  q053626481  q054243176  q054306561  q055537728  sizes_mingwi686.exe
[cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow]>
[cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow]> python3 -c "import subprocess;list_of_dirs_in_bash = subprocess.check_output(['ls']).decode().split('\n');print(list_of_dirs_in_bash)"
['a.py', 'q038171543', 'q049058700', 'q049499683', 'q049654022', 'q051073129', 'q051914879', 'q052051111', 'q052090348', 'q052720961', 'q053230645', 'q053626481', 'q053781370', 'q054243176', 'q054269984', 'q054306561', 'q055357490', 'q055537728', 'q056055568', 'sizes_mingwi686.exe', '']