命令不适用于子进程或os.popen,但适用于终端 [英] Command not works in subprocess or os.popen but works in terminal

查看:124
本文介绍了命令不适用于子进程或os.popen,但适用于终端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了很多方法来运行我的Shell脚本,但是python3脚本都无法使用这些方法。该命令非常简单,可以在终端中正常使用。这是我尝试不成功的方法:

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'

当我在终端中运行时,输出正确且有效,但是当我尝试在python脚本中运行,它将无法正常工作。
这是Shell脚本:

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"

python脚本的输出在这里:

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...


推荐答案

好,现在可以进行以下更改:

Ok, now it works with these changes:

这是shell脚本(commonBash.sh):

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

这是python脚本:

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

这篇关于命令不适用于子进程或os.popen,但适用于终端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆