Bash while循环调用Python脚本

时间:2010-03-01 23:30:31

标签: python bash while-loop

我想在Bash while循环中调用Python脚本。但是,我不太清楚如何恰当地使用Bash的while循环(也许是可变的)语法。我正在寻找的行为是,虽然文件仍然包含行(DNA序列),但我调用Python脚本来提取序列组,以便另一个程序(dialign2)可以对齐它们。最后,我将对齐添加到结果文件中。注意:我不是要迭代文件。为了让Bash while循环工作,我应该更改什么?我还想确保while循环将在每个循环上重新检查更改的file.txt。这是我的尝试:

#!/bin/bash
# Call a python script as many times as needed to treat a text file

c=1
while [ `wc -l file.txt` > 0 ] ; # Stop when file.txt has no more lines
do
    echo "Python script called $c times"
    python script.py # Uses file.txt and removes lines from it
    # The Python script also returns a temp.txt file containing DNA sequences
    c=$c + 1
    dialign -f temp.txt # aligns DNA sequences
    cat temp.fa >>results.txt # append DNA alignements to result file
done

谢谢!

4 个答案:

答案 0 :(得分:3)

不知道你为什么要这样做。

c=1
while [[ -s file.txt ]] ; # Stop when file.txt has no more lines
do
    echo "Python script called $c times"
    python script.py # Uses file.txt and removes lines from it
    c=$(($c + 1))
done

答案 1 :(得分:1)

尝试-gt消除shell元字符>

while [ `wc -l  file.txt`  -gt 0 ]
do
    ...
    c=$[c + 1]
done

答案 2 :(得分:0)

以下内容应该按照您的意愿进行:

#!/bin/bash

c=1
while read line; 
do
    echo "Python script called $c times"
    # $line contains a line of text from file.txt
    python script.py 
    c=$((c + 1))
done < file.txt

但是,没有必要使用bash来迭代文件中的行。你可以很容易地做到这一点,而不必离开python:

myfile = open('file.txt', 'r')

for count, line in enumerate(myfile):
    print '%i lines in file' % (count + 1,)
    # the variable "line" contains the line of text from the file.txt 

    # Do your thing here.

答案 3 :(得分:0)

@OP如果要循环浏览文件,只需在读取循环时使用。此外,您没有使用变量$ c以及行。您是否将每行传递给Python脚本?或者只是在遇到线路时调用Python脚本? (如果你这样做,你的脚本会很慢)

while true
do
    while read -r line
    do
       # if you are taking STDIN in myscript.py, then something must be passed to
       # myscript.py, if not i really don't understand what you are doing.

       echo "$line" | python myscript.py > temp.txt
       dialign -f temp.txt # aligns DNA sequences
       cat temp.txt >>results.txt
    done <"file.txt"
    if [ ! -s "file.txt" ]; break ;fi
done  

最后,你可以用Python完成所有事情。在Python中迭代“file.txt”的方法就是

f=open("file.txt"):
for line in f:
    print "do something with line"
    print "or bring what you have in myscript.py here"
f.close()