Download PDF using Python Requests

from pathlib import Path import requests filename = Path(‘myfile.pdf’) headers = {‘User-Agent’: ‘Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36’} url = ‘http://example.com/myfile.pdf’ response = requests.get(url, headers=headers) filename.write_bytes(response.content)

pymongo: Find documents by non-existence of a field

MongoDB: Search for documents without a property and add it with pymongo. from pymongo import MongoClient client = MongoClient(“myconnectionstring”) db = client.mydb cursor = db.mydocs.find({“myproperty”: None}) for document in cursor: print(document[“_id”]) db.mydocs.update({“_id”: document[“_id”]}, {“$set”: {“myproperty”:…

Python – Run two threads and stop them

In this post i extend an example found on stackoverflow.com, here’s how to launch two simultaneous threads and stop them after 5 seconds. import threading import time def doit(arg): t = threading.currentThread() while getattr(t, “do_run”,…

Compile and run a Python file

If you simply want to compile a file or group of python files from the terminal, the py_compile module can run as a script as follows: python -m py_compile file1.py file2.py file3.py Actually, to run…

Read the contents of an URL with Python

Python provides the urllib2 module that helps us in HTTP requests by defining functions and classes for redirecting, cookies, authentication and more. Here’s an example to take the content of a page and store it…