Archive

Author Archive

How to send a notification to your Android phone from a Python script

Problem
I have a long-running script and when something important happens, I’d like to send a notification to my Android phone. This way I shouldn’t be close to my machine. How to do it?

Solution
I found a very simple solution for this that can be set up in 3 minutes. This service can be found at https://notify.run/ . First, install the necessary package:

$ pip install notify-run

Then, register a channel:

$ notify-run register

It’ll print a QR code to the screen. Scan it with your phone and it brings you to a page where you can accept the notifications to your phone. Then, you can send notifications with the following Python snippet:

from notify_run import Notify

notify = Notify()
notify.send('sent from my Python script')

As can be seen, you don’t need to specify the name of the channel. It’s because it’s stored in the file ~/.config/notify-run and the notify_run module picks it up automatically.

You can also send a message to the channel from the command line, thus you can integrate it in any application:

curl https://notify.run/<channel_id> -d "message goes here"

Links

Advertisements
Categories: python Tags: , , , ,

How to create an executable file from a Python script?

February 10, 2019 Leave a comment

I made a sample project with explanation. You can find it here: https://github.com/jabbalaci/PythonEXE .

I also made a YouTube video that explains everything step-by-step:

Update (20190212): this project of mine got included in PyCoder’s Weekly #355 under the title “PythonEXE: How to Create an Executable File From a Python Script?“.

Categories: python Tags: , , , ,

pdfmanip

January 6, 2019 Leave a comment

Today I wrote a simple PDF manipulation CLI tool. You can find it here: https://github.com/jabbalaci/pdfmanip .

Categories: python Tags: ,

How old are you in days?

August 14, 2018 Leave a comment

Problem
You want to calculate how old you are in days.

Solution
Let’s use a popular 3rd party date/time library for this purpose called pendulum.

As an example, let’s take Arnold Schwarzenegger, who was born on July 30, 1947. So let’s answer the following question: how old is Schwarzenegger today?

>>> import pendulum
>>> 
>>> born = pendulum.parse("1947-07-30")
>>> born
DateTime(1947, 7, 30, 0, 0, 0, tzinfo=Timezone('UTC'))
>>> today = pendulum.now()
>>> today
DateTime(2018, 8, 14, 21, 32, 33, 248489, tzinfo=Timezone('Europe/Budapest'))
>>> 
>>> diff = today - born
>>> diff
<Period [1947-07-30T00:00:00+00:00 -> 2018-08-14T21:32:33.248489+02:00]>
>>> 
>>> diff.in_years()
71
>>> diff.in_words()
'71 years 2 weeks 1 day 19 hours 32 minutes 33 seconds'
>>> diff.in_days()
25948
Categories: python Tags: ,

table2csv

July 25, 2018 Leave a comment

Problem
I wanted to extract a table from an HTML. I wanted to import it to Excel, thus I wanted it in CSV format for instance.

Solution
table2csv can do exactly this. Visit the project’s page on GitHub for examples.

Note that I could only make it work under Python 2.7.

Categories: python Tags: , , , ,

MonkeyType: generate static type annotations automatically

July 25, 2018 Leave a comment

In my previous post I wrote about mypy that can check type annotations.

MonkeyType (from Instagram) is a project that generates static type annotations by collecting runtime types. It can be a great help if you don’t want to do it manually.

I tried it and it works surprisingly well! However, the idea is to generate type annotations with MonkeyType and review the hints. “MonkeyType’s annotations are an informative first draft, to be checked and corrected by a developer.

Read the README of the project for an example.

Categories: python Tags: , , ,

mypy — optional static typing

July 25, 2018 Leave a comment

Problem
Python is awesome, it’s my favourite programming language (what a surprise :)). Dynamic typing allows one to code very quickly. However, if you have a large codebase (and I ran into this problem with my latest project JiVE), things start to get complicated. Let’s take an example:

def extract_images(html):
    lst = []
    ...
    return lst

If I look at this code, then what is “html”? Is it raw HTML (string), or is it a BeautifulSoup object? What is the return value? What is in the returned list? Does it return a list of URLs (a list of strings)? Or is it a list of custom objects that wrap the URLs?

If we used a statically-typed language (e.g. Java), these questions wouldn’t even arise since we could see the types of the parameters and the return value.

Solution
I’ve heard about mypy but I never cared to try it. Until now… “Mypy is an experimental optional static type checker for Python that aims to combine the benefits of dynamic (or “duck”) typing and static typing. Mypy combines the expressive power and convenience of Python with a powerful type system and compile-time type checking.” (source)

Thus, the example above could be written like this:

from typing import List
from bs4 import BeautifulSoup
from myimage import Image

def extract_images(html: BeautifulSoup) -> List[Image]:
    lst = []
    ...
    return lst

And now everything is clear and there is no need to carefully analyse the code to figure out what goes in and what comes out.

This new syntax was introduced in Python 3.6. Actually, if you run such an annotated program, the Python interpreter ignores all these hints. So Python won’t become a statically-typed language. If you want to make these hints work, you need to use “mypy”, which is a linter-like static analyzer. Example:

$ pip install mypy    # you can also install it globally with sudo
$ mypy program.py     # verify a file
$ mypy src/           # verify every file in a folder

With mypy you can analyse individual files and you can also analyse every file in a folder.

If you get warnings that mypy doesn’t find certain modules, then run mypy with these options:

$ mypy program.py --ignore-missing-imports --follow-imports=skip

IDE support
I highly recommend using PyCharm for large(r) projects. PyCharm has its own implementation of a static type checker. You can use type hints out of the box and PyCharm will tell you if there’s a problem. It’s a good idea to combine PyCharm with Mypy, i.e. when you edit the code in the IDE, run mypy from time to time in the terminal too.

Getting started
To get started, I suggest watching/reading these resources:

It’s really easy to get started with mypy. It took me only 2 days to fully annotate my project JiVE. Now the code is much easier to understand IMO.

Tips
If you have a large un-annotated codebase, proceed from bottom up. Start to annotate files that are leaf nodes in the dependency tree/graph. Start with modules that are most used by others (e.g. helper.py, utils.py, common.py). Then proceed upwards until you reach the main file (that I usually call main.py, which is the entry point of the whole project).

You don’t need to annotate everything. Type hints are optional. The more you add, the better, but if there’s a function that you find difficult to annotate, just skip it and come back to it later.

Annotate the function signatures (type of arguments, type of the return value). Inside a function I don’t annotate every variable. If mypy drops a warning and says a variable should be annotated, then I do it.

Sometimes mypy drops an error on a line but you don’t want to annotate it. In this case you can add a special comment to tell mypy to ignore this line:

    ...    # type: ignore

If a function’s signature has no type hints at all, mypy will skip it. If you want mypy to check that function, then add at least one type hint to it. You can add for instance the return type. If the function is a procedure, i.e. it has no return value, then indicate None as the returned type:

def hello() -> None:
    print("hello")

You can add type hints later. That is, you can write your project first, test it, and when it works fine, you can add type hints at the end.

When to use mypy?
For a small script it may not be necessary but it could add a lot to a large(r) project.

Notes
If you read older blog posts, you may find that they mention the package “mypy-lang”. It’s old. Install the package “mypy” and forget “mypy-lang”. More info here.

Categories: python Tags: , , , ,