halloleo
halloleo

Reputation: 10464

Use a Python package from a script without installing it

I have a python script which will be executed by the system python (on OSX /usr/bin/python). This script uses an external package (in my case PyYaml).

How can I provide the package without pip-installing it into the system python. I do not want to create a virtual environment for this script either, because the script is meant to run on other "vanilla" OSX machines as well.

I'm thinking of creating a directory under the same path where the script resides and "dumping" the external package there. But in what form? And what do I have to do in my script, so that it "sees" the locally dumped package? Just amend sys.path?

Upvotes: 0

Views: 1843

Answers (2)

halloleo
halloleo

Reputation: 10464

As an enhancement to Synedraacus's answer: (*)

You can copy the whole yaml subdirectory of PyYAML into your script directory (which is in the PyYAML zip file lib/yaml if you use Python 2 and lib3/yaml for Python 3). Then you can use it in your code as if you had PyYaml pip-installed. Just write:

import yaml

This works of course only if you don't want to use the C backend.


(*) I tried to add this detail to Synedraacus's answer, but my edit got rejected. Therefore I add this enhancement as a separate answer.

Upvotes: 0

Synedraacus
Synedraacus

Reputation: 1055

You can just copypaste the pyYaml's *.py files into your script directory and import them like you would import your own modules. This is not the most beautiful solution, but it works.
If you intend to use C backend, it'd be more difficult. You either need to make sure your installer compiles them correctly, or make platform-dependent distributions with the compiled C modules. But those are there for speed and pure Python code can be enough.

Upvotes: 1

Related Questions