我有一个 Python 程序,它将 url 作为运行时参数。我想通过创建一个“包装器”来处理包含 url 列表作为输入的 CSV 文件来修改它。该脚本应针对 CSV 文件中的每一行执行一次。
这是我的简单脚本“myscript.py”:
#! /usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('url', help='input URL')
args = parser.parse_args()
print('This is the argument')
print(args.url)
我和它一起跑步
python3 myscript.py https://www.bbc.co.uk
它输出:
This is the argument
https://www.bbc.co.uk
现在,如果我有一个 CSV 文件“urls.csv”,我希望能够运行:
python3 myscript.py urls.csv
该脚本应运行必要的次数以根据要生成的文件 urls.csv 中的 url 数量生成输出(例如):
This is the argument
https://www.bbc.co.uk
This is the argument
https://www.itv.com
This is the argument
https://www.channel4.com
This is the argument
https://www.channel5.com
我更喜欢“包装器”方法,而不是修改现有脚本中的“argparse”命令。
如果您不需要传递 URL 作为参数,您可以像这样修改脚本:
#!/usr/bin/env python3
import csv
import sys
# Check if a CSV file was actually provided in the arguments
if len(sys.argv) != 2:
print("Usage: python3 myscript.py <urls.csv>")
sys.exit(1)
csv_file = sys.argv[1]
with open(csv_file, 'r') as file:
reader = csv.reader(file)
for row in reader:
if row: # Checks if the row is not empty
print('This is the argument')
print(row[0])
此代码从指定的 CSV 文件中读取 URL 并一一打印它们。你可以像这样运行它:
python3 myscript.py urls.csv
。
我无法纯粹用Python得到满意的结果,所以我恢复到Autohotkey(ahk)来提供一个“包装器”。
#Persistent
SetWorkingDir %A_ScriptDir%
ProcessCSV(filePath) {
if !FileExist(filePath) {
MsgBox, CSV file not found: %filePath%
ExitApp
}
FileRead, csvContent, %filePath%
Loop, Parse, csvContent, `r, `n
{
line := A_LoopField
url := Trim(line)
if (url != "")
{
; %ComSpec% /k keeps the cmd window open! Remove to run silently.
RunWait, %ComSpec% /k python.exe myscript.py "%url%"
}
}
}
; Get CSV file
FileSelectFile, selectedFile, 3,, Select a CSV file, CSV Files (*.csv)
if (selectedFile = "")
{
MsgBox, No file selected.
ExitApp
}
ProcessCSV(selectedFile)
ExitApp
您可以使用简单的 shell 循环。
while read -r url; do
python myscript.py "$url"
done < urls.csv
假设文件的每一行只是一个 URL。如果有更多字段,您需要从中提取 URL。在shell脚本中解析CSV文件有很多问题。