【发布时间】:2012-03-17 13:29:53
【问题描述】:
如何在 python 中进行文件读取循环?我正在尝试将我的 bash 脚本转换为 python,但之前从未编写过 python。仅供参考,我在成功的命令竞赛后读取文件的原因是确保它读取最新的编辑(例如,如果 URL 被重新排序)。 谢谢!
#!/bin/bash
FILE=$1
declare -A SUCCESS=()
declare -A FAILED=()
for (( ;; )); do
# find a new link
cat "$FILE" > temp.txt
HASNEW=false
while read; do
[[ -z $REPLY || -n ${SUCCESS[$REPLY]} || -n ${FAILED[$REPLY]} ]] && continue
HASNEW=true
break
done < temp.txt
[[ $HASNEW = true ]] || break
# download
if axel --alternate --num-connections=6 "$REPLY"; then
echo
echo "Succeeded at $DATETIME downloading following link $REPLY"
echo "$DATETIME Finished: $REPLY" >> downloaded-links.txt
echo
SUCCESS[$REPLY]=.
else
echo
echo "Failed at $DATETIME to download following link $REPLY"
echo "$DATETIME Failed: $REPLY" >> failed-links.txt
FAILED[$REPLY]=.
fi
# refresh file
cat "$FILE" > temp.txt
while read; do
[[ -z ${SUCCESS[REPLY]} ]] && echo "$REPLY"
done < temp.txt > "$FILE"
done
这就是我到目前为止所得到的工作,我不知道如何让它在每次成功执行 axel 行之后读取文件的第一行,就像 bash 脚本一样。我对子进程调用的其他选项(例如线程)持开放态度,但我不确定如何使其工作。
#!/usr/bin/env python
import subprocess
from optparse import OptionParser
# create command line variables
axel = "axel --alternate --num-connections=6 "
usage = "usage: %prog [options] ListFile.txt"
parser = OptionParser(usage=usage)
parser.add_option("-s", "--speed", dest="speed",
help="speed in bits per second i.e. 51200 is 50kps", metavar="speedkbps")
(opts, args) = parser.parse_args()
if args[0] is None:
print "No list file given\n"
parser.print_help()
exit(-1)
list_file_1 = args[0]
try:
opts.speed
except NoSpeed:
with open(list_file_1, 'r+') as f:
for line in f:
axel_call = axel + "--max-speed=" + opts.speed + " " + line
# print ("speed option set line send to subprocess is: " + axel_call)
subprocess.call(axel_call, shell=True)
else:
with open(list_file_1, 'r+') as f:
for line in f:
axel_call = axel + line
# print ("no speed option set line send to subprocess is:" + axel_call)
subprocess.call(axel_call, shell=True)
【问题讨论】:
-
到目前为止您尝试过什么?改进或修复已经存在的方法比从头开始编写一个方法要花费更少的精力......
-
那个 bash 代码甚至可以做什么?当你可以只使用
< "$FILE"时,为什么它会先使用cat "$FILE" > temp.txt,然后再使用< temp.txt?
标签: python bash loops scripting