参考になればと思い、例を書きました。これは、urls.txt
処理するジョブを一覧表示するファイルと、複数のプロセスを使用してダウンロードする xdownloader.py ファイルで構成されます。Python 2.7 を実行している Linux マシンでテストしました。
xdownloader.py
from multiprocessing import Process
import urllib2
def main():
try:
# Read URLs/Destinations from a file
jobs = []
with open("urls.txt","r") as ifile:
for line in ifile:
jobs.append(line.split(" "))
# Create a process list to keep track of running processes
process_list = []
# Iterate through our jobs list
for url, save_to in jobs:
# Create a new process that runs function 'download'
p = Process(target=download, args=(url, save_to))
# Save it to a list
process_list.append(p)
# Start the process
p.start()
except KeyboardInterrupt:
print("Received keyboard interrupt (ctrl+c). Exiting...")
finally:
# Wait for all processes to finish before exiting
for process in process_list:
# Wait for this process to finish
process.join()
print("All processes finished successfully!")
def download(url, destination):
# Open a request
request = urllib2.urlopen(url)
# Read and save the webpage data to a file
with open(destination, "w+") as save_file:
print("Downloading {0}".format(url))
save_file.write(request.read())
if __name__=="__main__":
main()
urls.txt
http://google.com google.html
http://yahoo.com yahoo.html
http://news.google.com news.google.html
http://reddit.com reddit.html
http://news.ycombinator.com news.ycombinator.html
実行すると、次のpython xdownloader.py
ようになります。
mike@localhost ~ $ python xdownloader.py
Downloading http://news.ycombinator.com
Downloading http://reddit.com
Downloading http://news.google.com
Downloading http://google.com
Done downloading http://google.com
Done downloading http://news.ycombinator.com
Done downloading http://reddit.com
Downloading http://yahoo.com
Done downloading http://news.google.com
Done downloading http://yahoo.com
ジョブが非同期で実行されていることがわかります...一部のジョブは、他のジョブよりも早く開始されますが、終了は遅くなります。(news.google.com を見ています!) この例がニーズに合わない場合は、コメントでお知らせください。