命令在子进程或 os.popen 中不起作用,但在终端中起作用

Command not works in subprocess or os.popen but works in terminal

我尝试了很多 运行 我的 shell 脚本的方法,但是 none 这些方法来自 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...

好的,现在它适用于这些更改:

这是 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