【问题标题】:Getting parameters from a file via shell script into python script in the right format通过 shell 脚本将参数从文件中获取到正确格式的 python 脚本中
【发布时间】:2010-07-19 16:04:16
【问题描述】:

我有以下 shell 脚本:

#! /bin/sh

while read page_section
  page=${page_section%%\ *}
  section=${page_section#* }     #NOTE: `%* }` is NOT a comment

  wget --quiet --no-proxy www.cs.sun.ac.za/hons/$page -O html.tmp & wait

#  echo ${page_section%%\ *} # verify correct string chopping
#  echo ${page_section#* }   # verify correct string chopping

  ./DokuWikiHtml2Latex.py html.tmp $section & wait
done < inputfile

还有一个像这样的输入文件:

doku.php?id=ndewet:tools:tramonitor TraMonitor
doku.php?id=ndewet:description Implementation -1
doku.php?id=ndewet:description Research\ Areas -1

该脚本会下载inputfile 中指定的多个网页,然后必须将行的其余部分(例如“实施 -1”或“研究\领域 -1”)传递给 Python 脚本。

现在是粘性位。处理此示例文件的第三行时,它将“Research\Areas”作为两个单独的参数传递给 python 脚本,如下所示:

>>> print sys.argv
['./DokuWikiHtml2Latex.py', 'html.tmp', 'Research', 'Areas', '-1']

如何将输入文件中的“研究领域”等多字部分转换为 python 脚本的单个参数?我试过转义'\',并且也在做

./DokuWikiHtml2Latex.py html.tmp `echo ${section#* }`

除此之外,但无济于事。

输入行末尾的数字是另一个参数,但可选。

【问题讨论】:

    标签: python bash argument-passing


    【解决方案1】:

    在 $section 周围加上引号:

    ./DokuWikiHtml2Latex.py html.tmp "$section" & wait
    

    【讨论】:

      【解决方案2】:

      read 做解析工作:

      while read page section rest
      do
          echo "Page: $page"
          echo "Section: $section"
      done < inputfile
      

      为了优雅地处理可选参数,请使用数组:

      while read -a fields
      do
          wget --quiet --no-proxy "www.cs.sun.ac.za/hons/${fields[0]}" -O html.tmp
          unset "fields[0]"
          ./DokuWikiHtml2Latex.py html.tmp "${fields[@]}"
      done < inputfile
      

      总是引用你的变量!

      【讨论】:

      • 您应该在您取消设置的数组元素周围加上引号以防止文件通配:unset "fields[0]"(如果有一个名为“fields0”的文件)。演示:test=(1 2 3); touch test0; unset test[0]; declare -p test; unset "test[0]"; declare -p test
      • 不客气。我忘了证明一个名为 test0 的变量(如果存在)会因为文件的通配和存在而被取消设置:test=(1 2 3); test0=4; touch test0; unset test[0]; echo "test0 = $test0"; declare -p test; unset "test[0]"; declare -p test
      【解决方案3】:

      通常可以使用引号将多字参数作为一个参数传递,因此:

      doku.php?id=ndewet:description "Research Areas" -1
      

      【讨论】:

        猜你喜欢
        • 2012-06-03
        • 2018-05-19
        • 1970-01-01
        • 2014-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-06
        • 2014-10-05
        相关资源
        最近更新 更多