简体   繁体   中英

Python equivalent/emulator of Bash “parameter expansion”

I have a bash script that I use to update several computers in my house. It makes use of the deborphan program which identifies programs that are no longer required on my system (Linux obviously).

The bash script makes use of bash's parameter expansion which enables me to pass deborphan's results to my package manager (in this case aptitude):

aptitude purge $(deborphan --guess-all) -y

deborphan's results are:

python-pip
python3-all

I would like to convert my bash script into python (partly as a learning opportunity, as I am new to python), but I have run into a significant snag. My obvious start for the python script is

subprocess.call(["aptitude", "purge", <how do I put the deborphan results here?>, "-y"])

I have tried a separate subprocess.call for a parameter inside the above subprocess.call just for deborphan and that fails.

Interestingly enough I cannot seem to capture the deborphan results with:

deb = subprocess.call(["deborphan", "--guess-all"])

to pass deborphan's results as a variable for the parameter either.

Is there anyway to emulate Bash's parameter expansion in python?

You can use + to concatenate lists:

import subprocess as sp
deborphan_results = sp.check_output(…)
deborphan_results = deborphan_results.splitlines()
subprocess.call(["aptitude", "purge"] + deborphan_results + ["-y"])

(if you're using a Python version below 2.7, you can use proc = sp.Popen(…, stdout=sp.PIPE); deborphan_results, _ = proc.communicate() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM