我正在从文件中获取URL,以便他们使用curl来下载图像,在URL中进行更改之后URL=${URL%$'\r'}
,我正在运行循环以读取每一行,输入变量并通过TensorFlow对图像进行分类(如果它们是信息图形)它应该执行if语句,否则应该执行else语句。在执行bash脚本时,if和else语句都将被执行
在执行else语句时,在打印echo ${var%$'something'}
时不会打印任何内容……此外,从键盘上获取输入内容时脚本运行良好。
#!/bin/bash
while IFS= read -r file
do
url=${file%$'\r'}
var=`python test_python_classify.py $url`
if [ $var == 1 ]
then
echo $var
curl -o image.png $url
python description1.py $url
else
echo "\n\n\n"
echo ${var%$'yoyo'}
echo "lol"
fi
done < url.txt
编辑:循环正在执行两次。是由于更改字符串引起的还是什么,请帮忙。
错误:
Traceback (most recent call last):
File "test_python_classify.py", line 3, in <module>
URL = sys.argv[1]
IndexError: list index out of range
./pipeline1.sh: line 8: [: ==: unary operator expected
有几个错误。
首先$url
是空的(可能是脚本中的空行),这使得python在尝试访问参数时失败。这就是该错误的含义:
URL = sys.argv[1]
IndexError: list index out of range
然后在脚本中混合使用返回代码和返回值:
var=`python test_python_classify.py $url`
if [ $var == 1 ]
then
python脚本以1返回码退出,它不会打印1。实际上,您的脚本不打印任何内容(崩溃跟踪转到stderr
),因此$var
为空,并且由于没有用引号。
./pipeline1.sh: line 8: [: ==: unary operator expected
如果您需要测试返回码,$?
还可以过滤空网址(我的bash生锈了,但是应该可以使用):
if [ ! -z "$url" ]
then
python test_python_classify.py $url
if [ $? == 1 ]
then
如果python脚本打印了一个值,请首先测试返回代码以查看是否成功,然后检查打印的值
if [ ! -z "$url" ]
then
var = $(python test_python_classify.py $url)
# check if returncode is 0, else there was an error
if [ $? == 0 ]
then
# protecting return with quotes doesn't hurt
if [ "$var" == 1 ]
then
如评论中所建议,这可能会使用主要的完整python重写,这将简化所有这些bash / python接口问题。(未经测试)类似:
import sys,subprocess # we could use python script functions too
with open("url.txt") as f:
for line in f:
url = line.rstrip()
if url:
output = subprocess.check_output([sys.executable,"test_python_classify.py",url])
output = output.decode().strip() # decode & get rid of linefeeds
if output == "1":
print("okay")
subprocess.check_call(["curl","-o","image.png",url])
subprocess.check_call([sys.executable,"description1.py",url])
else:
print("failed: {}: {}".format(url,output))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句