python 脚本的并行处理
parallel processing of python script
我有一个 python 脚本,它一次接受一个输入并处理它。
我想 运行 同时编写与不同输入并行的脚本。类似 50 或 100 次,但使用来自 txt 文件的不同输入提要。
我执行如下脚本:
python script.py -d url1
然后
python script.py -d url2
然后
python script.py -d url3
我不想一次输入一个参数,而是想从文本文件中输入这些 url 并并行处理它们。
我在 bash shell 中使用 gnu-parallel 尝试了此脚本 运行ning 但 bash 脚本不是 运行s python shell,因此出现错误。
代码如下---
#!/usr/bin/env bash
doit() {
host=""
~/script/python script1.py -d $host
}
export -f doit
cat "" | parallel -j50 -k doit
txt文件内容---
url1.com
url2.com
url3.com
--------
url1000.com
url_any.com
GNU Parallel 的替代方法是使用 Python subprocess 重复执行命令。
这是使用 Python 2.7.
的示例
首先,您的代码需要读取文本文件以将所有参数分配给列表。
with open('<Arguments text file location>') as f:
arguments = f.read().splitlines()
然后你使用循环 运行 使用子进程为每个参数执行一次命令。
import subprocess
procs = []
for argument in arguments:
cmd = 'python script.py %(argument)' % {'argument': argument}
procs.append(
subprocess.Popen(cmd, shell=True)
)
exit_codes = [p.wait() for p in procs]
使用 GNU Parallel,像这样:
parallel --dry-run -a arguments.txt python script.py
假设您的参数在 "arguments.txt"
.
中每行一个
如果需要,请使用 parallel -k ...
保持输出顺序。
使用parallel --bar ...
获取进度条。
我有一个 python 脚本,它一次接受一个输入并处理它。 我想 运行 同时编写与不同输入并行的脚本。类似 50 或 100 次,但使用来自 txt 文件的不同输入提要。
我执行如下脚本:
python script.py -d url1
然后
python script.py -d url2
然后
python script.py -d url3
我不想一次输入一个参数,而是想从文本文件中输入这些 url 并并行处理它们。
我在 bash shell 中使用 gnu-parallel 尝试了此脚本 运行ning 但 bash 脚本不是 运行s python shell,因此出现错误。
代码如下---
#!/usr/bin/env bash
doit() {
host=""
~/script/python script1.py -d $host
}
export -f doit
cat "" | parallel -j50 -k doit
txt文件内容---
url1.com
url2.com
url3.com
--------
url1000.com
url_any.com
GNU Parallel 的替代方法是使用 Python subprocess 重复执行命令。
这是使用 Python 2.7.
的示例首先,您的代码需要读取文本文件以将所有参数分配给列表。
with open('<Arguments text file location>') as f:
arguments = f.read().splitlines()
然后你使用循环 运行 使用子进程为每个参数执行一次命令。
import subprocess
procs = []
for argument in arguments:
cmd = 'python script.py %(argument)' % {'argument': argument}
procs.append(
subprocess.Popen(cmd, shell=True)
)
exit_codes = [p.wait() for p in procs]
使用 GNU Parallel,像这样:
parallel --dry-run -a arguments.txt python script.py
假设您的参数在 "arguments.txt"
.
如果需要,请使用 parallel -k ...
保持输出顺序。
使用parallel --bar ...
获取进度条。