如何修复"在检查条件是否其他语句也被执行后在 bash 中"?



我正在从文件中获取URL,以便它们使用curl下载图像,在URLURL=${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 "nnn"
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为空,并且由于您没有使用引号保护变量而出现shell语法错误。

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

最新更新