【问题标题】:How do I convert this bash loop to python?如何将此 bash 循环转换为 python?
【发布时间】: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 代码甚至可以做什么?当你可以只使用&lt; "$FILE" 时,为什么它会先使用cat "$FILE" &gt; temp.txt,然后再使用&lt; temp.txt

标签: python bash loops scripting


【解决方案1】:

读取文件的完全 Pythonic 方式如下:

with open(...) as f:
    for line in f:
        <do something with line>

with 语句处理打开和关闭文件,包括是否在内块中引发异常。 for line in f 将文件对象 f 视为一个可迭代对象,它会自动使用缓冲 IO 和内存管理,因此您不必担心大文件。

应该有一种——最好只有一种——明显的方法。

【讨论】:

  • 是否可以使用 suprocess 调用?即with open(list_file_1, 'r+') as f: for line in f: subprocess.call(axel, list_file_1, shell=True) (你怎么让stackoverflow在带有注释的代码中尊重空格?)
  • 您是否有任何特定原因要生成子进程?您可以进行子进程调用,但在这种情况下,我发现使用线程是更好的选择。这样以后整理来自不同子进程的数据变得很痛苦,而位于同一进程空间中的线程更加优雅。
【解决方案2】:

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    相关资源
    最近更新 更多