this post was submitted on 14 Jun 2023
8 points (100.0% liked)

Python

1921 readers
1 users here now

A community for talking about the Python programming language.

founded 1 year ago
MODERATORS
 

So I made a small little command-line utility for myself just for practice, but I had a hard time figuring out how to actually turn it into something I can just use on the command line with no fuss. It uses a virtual environment as Python packages should, so it needs to be run in that environment and I was having trouble figuring out how to do it.

But then I remembered that pipx runs application in a virtual environment, and after checking the docs, I found out that it allows installing local packages by just pointing install at the package directory. So I did, and after setting up the command name as a project script that points to main it ended up working.

I haven't ever heard of anyone doing something like this for a personal program though. Is something like this a bad idea? Is it over engineering or error prone? Is there another way that most people do something like this?

top 3 comments
sorted by: hot top controversial new old
[–] [email protected] 4 points 1 year ago* (last edited 1 year ago) (1 children)

Perfect use case. pipx is awesome for Python! Glad you found a great easy solution.

Is it over engineering or error prone?

Nope. pipx is like a big guard rail to keep you from doing error prone things with system Python.

In these examples we'll assume your venv is at /home/TrueBlue/project/venv

Is there another way...?

  • shebang: Set your #! to point at your Python venv runtime
    #!/home/TrueBlue/project/venv python3
    Now you can just run your Python file and it'll use the correct Python runtime.
  • poetry can be useful for running personal projects using poetry run.
  • In linux you can use an alias to create to call your venv Python runtime with your package.

e.g. I want to use a new command named sdf to call my app.

alias sdf="/home/TrueBlue/project/venv/bin/python3 my_app.py"

[–] [email protected] 1 points 1 year ago* (last edited 1 year ago)

Great ideas! You can also set top of script to be:

#!/usr/bin/env python3

That way it will work with environment Python. Runs against venv, as well.

[–] [email protected] 2 points 1 year ago

This seems ok to me. Over time you might come to regret it if you have many scripts and they want to use different package versions...

Another approach could be to write a shell script which loads the virtual environment and then starts the main script. something like

cd /home/rimu/path_to_my_script/
source venv/bin/activate
python myscript.py

Put your shell script in ~/bin and ensure that ~/bin is in your $PATH.

load more comments
view more: next ›