Run poetry-installed python scripts in optimized mode

Viewed 663

I have a pyproject.toml:

[tool.poetry.scripts]
# aka entry points or console scripts for setup.py users
merge = 'mypackage.__main__:main'

mypackage contains some assert statements that I do not want run in production, but I would like to run these scripts in "optimized" mode.

Is this possible to do with a poetry script?

2 Answers

When you install a package with a console entrypoint, setuptools' or poetry's installer just creates a simple executable shim in the active python interpreter's bin/. The shim decides which python interpreter will be called to execute your package's code, and by extension also which flags accompany the call.

So, first of all you need to run which merge in order to find out where the shim lives. It should look similar to this, but the exact look is very os-dependent:

#!/home/user/dev/merge/venv/bin/python3
# EASY-INSTALL-ENTRY-SCRIPT: 'mypackage','console_scripts','merge'
import re
import sys
...

Now just append -O to the shebang, and you're done. I tested it on ubuntu and it worked just fine.


Caveats:

  • shebangs only accept a single flag, so you better only need this one
  • you need to re-add the flag after every single poetry install
  • in a similar vein, you can't rig your .wheel to enforce this, in case you want to install this somewhere remote
Related