问题
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