从.sh到Python获取变量值

2024-04-29 16:33:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.sh文件,可以在树莓皮上生成一张图片。在这个文件里我有以下内容:

你知道吗配置.sh地址:

#!/bin/bash
suffix=$(date +%H%M%S)  
cd /home/pi/photobooth_images/  
sudo cp image1.jpg /usb/photobooth_images/image-${suffix}-1.jpg  
sudo convert -size 1800x1200 xc:white \  
        image1.jpg -geometry 1536x1152+240+24 -composite \   
    /home/pi/template/logo.png -geometry 192x1152+24+24 -composite \  
        PB_${suffix}.jpg  
sudo cp PB_${suffix}.jpg /usb/photobooth_montage/PB_${suffix}.jpg  
sudo rm /home/pi/photobooth_images/*  
returnvalue=PB_${suffix}.jpg  
echo "$returnvalue"  

这里我要做的是获取它在Python中生成的PB_${suffix}.jpg“returnvalue”值(文件名)。现在我的Python程序有了这一行,它运行上面的.sh文件。你知道吗

你知道吗主.py地址:

return_value = subprocess.call("sudo ./" + config.sh, shell=True)  
print "The Value is: " + str(return_value) + " This value from Python"  

The output I get is this  
[08:33:02 04-10-2016] [PHOTO] Assembling pictures according to 1a template.  
PB_083302.jpg  
The Value is: 0 This value from Python  
The output I am expected should be something like "PB_070638.jpg"  

非常感谢您的帮助。你知道吗


Tags: 文件thehomeisvalue地址shpi
2条回答

尝试将Popen构造函数与stdout arg一起使用:

subprocess.Popen(['"sudo ./" + config.sh'], stdout=subprocess.PIPE)

另请参见: Get return value from shell command in python

另外,这里还有Python文档中关于Popen的更多信息。 https://docs.python.org/2/library/subprocess.html#popen-constructor

这是因为subprocess.call只返回执行脚本的返回代码(documentation)。您需要脚本返回的实际输出,因此应该使用check_output,并避免使用shell=True

subprocess.check_output(["sudo", "./", config.sh])

您可能还想通过sudo修改在没有root权限的情况下运行脚本。它看起来不像应该使用root权限运行的东西。你知道吗

相关问题 更多 >