Python中Bash "参数扩展" 的等价物/模拟器
我有一个bash脚本,用来更新我家里的几台电脑。这个脚本使用了一个叫deborphan的程序,它可以找出系统中不再需要的程序(显然是Linux系统)。
这个bash脚本利用了bash的参数扩展功能,这样我就可以把deborphan的结果传递给我的包管理器(在这个例子中是aptitude):
aptitude purge $(deborphan --guess-all) -y
deborphan的结果是:
python-pip
python3-all
我想把我的bash脚本转换成python(部分原因是想学习,因为我对python还很陌生),但我遇到了一个比较大的问题。我在python脚本中的明显起点是:
subprocess.call(["aptitude", "purge", <how do I put the deborphan results here?>, "-y"])
我尝试在上面的subprocess.call中为deborphan使用一个单独的subprocess.call,但这样做失败了。
有趣的是,我似乎无法用以下方式捕获deborphan的结果:
deb = subprocess.call(["deborphan", "--guess-all"])
也无法将deborphan的结果作为参数传递。
有没有办法在python中模拟bash的参数扩展呢?
1 个回答
6
你可以用 +
来连接两个列表:
import subprocess as sp
deborphan_results = sp.check_output(…)
deborphan_results = deborphan_results.splitlines()
subprocess.call(["aptitude", "purge"] + deborphan_results + ["-y"])
(如果你用的是 Python 2.7 之前的版本,可以用 proc = sp.Popen(…, stdout=sp.PIPE); deborphan_results, _ = proc.communicate()
)