我已经尝试了很多方法来运行我的shell脚本,但是python3脚本都没有这些方法。该命令非常简单,可以在终端中正常使用。这是我尝试不成功的方法:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
dat = os.popen('sh commonBash.sh').read()
print(dat)
if "no" in dat:
print('Not found')
status = 'Install'
else:
print('Found')
status = 'Remove'
当我在终端中运行时,输出正确且有效,但是当我尝试在python脚本中运行时,它将无法正常工作。 这是shell脚本:
name="libreoffice" && dpkg-query -W $name && echo "$name"
python脚本的输出在这里:
dpkg-query: no packages found matching libreoffice # Here the $name is correct
# This is $name, which is an empty newline
Found # I don't know why, but the output is found
但是,当我运行实际程序时,同一部分的输出有所不同。在这里:
# Empty lines for print(dat) and echo "$name" also
# Why?
Found # And the result is still Found...
答案 0 :(得分:0)
好的,现在可以进行以下更改:
这是shell脚本(commonBash.sh):
name=libreoffice
dat=$(dpkg-query -W $name)
echo "Checking for "$name": "
echo "$dat"
if [ "" == "$dat" ]; then
echo "No "$name". Setting up "$name"..."
else
echo $name" is installed already."
fi
这是python脚本:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
dat = os.popen('bash commonBash.sh').read()
print(dat)
if "No" in str(dat):
print('Not found')
status = 'Install'
else:
print('Found')
status = 'Remove'
这是输出(现在是正确的):
dpkg-query: no packages found matching libreoffice
Checking for libreoffice:
No libreoffice. Setting up libreoffice...
Not found