我該如何做Python文件閱讀循環?我試圖將我的bash腳本轉換爲python,但從未寫過python。僅供參考,在閱讀成功的命令比賽後閱讀文件的原因是確保它讀取最近的編輯(例如,如果URL被重新排序)。 謝謝!如何將此bash循環轉換爲python?
#!/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
這是我到目前爲止這是工作了,我無法弄清楚如何使它的阿克塞爾線的像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)
你嘗試過這麼遠嗎?改進或修復現有的方法要比編寫一個很難的方法花費更少的努力... – 2012-02-28 03:01:38
這個bash代碼甚至做了什麼?爲什麼它執行'cat'$ FILE「> temp.txt',然後在使用'<」$ FILE「'代替時執行'
2012-02-28 03:07:10