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

蹲街弑〆低调 提交于 2019-12-13 20:09:20

问题


I've tried lots of methods to run my shell script but none of these works from python3 script. The command is very simple and works in terminal without problem. Here's what I've tried without sucsess:

#!/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'

When I run in terminal the output is correct and working, but when I try to run in python script it won't work. Here's the shell script:

name="libreoffice" && dpkg-query -W $name && echo "$name"

The output of the python script is here:

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

However when I run the actual program, the output of the same part is somehow different. Here it is:

           # Empty lines for print(dat) and echo "$name" also
           # Why?
Found      # And the result is still Found...

回答1:


Ok, now it works with these changes:

Here's the shell script (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

Here's the python script:

#!/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'

And here's the output (now it's correct):

dpkg-query: no packages found matching libreoffice
Checking for libreoffice: 

No libreoffice. Setting up libreoffice...

Not found


来源:https://stackoverflow.com/questions/57119935/command-not-works-in-subprocess-or-os-popen-but-works-in-terminal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!