Bash中的while循环调用Python脚本
我想在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
下面的代码应该能实现你想要的功能:
#!/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.
1
试试用 -gt
来去掉命令行中的特殊符号 >
while [ `wc -l file.txt` -gt 0 ]
do
...
c=$[c + 1]
done
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