首页 > 解决方案 > 如何在检查 if 条件 else 语句也被执行后修复“在 bash 中”?

问题描述

我正在从文件中获取 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

标签: pythonbashioautomation

解决方案


有几个错误。

首先$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

如果您需要测试返回代码,$?还需要过滤空 url(我的 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))

推荐阅读