Run command after spawning Poetry Shell

Viewed 3813

I work with Python Poetry and need to automate the process. Specifically, everytime I need to go to a directory with

cd /work/directory

And spawn a poetry shell with

poetry shell

and again go to another directory

cd /other/directory

to finish the work.

I would love to automate this with a small script like

#!/bin/bash

cd /work/directory
poetry shell
cd /other/directory
# do work

However whenever I run this script, I get stucks at poetry shell. Is there any option like bash's -c so that I can do following?

poetry shell -c "cd /other/directory && do work"
3 Answers

Probably you want to run a python script using the poetry virtual environment. In that case, I think you should be using simple the command

poetry run {your_command}

For a more practical example you can run a python script as follows

poetry run python myscript.py

which will use the poetry virtual environment you already created with poetry install.

ran into the same problem. this was posted by someone in the poetry discord server:

I am not sure what running poetry shell exactly entails in all details. But... Maybe it is good enough for you to just activate the virtual environment. And if what you want to do is not interactive work on the command line, then activating the environment might not even be necessary.

Typically you would first need to identify the path to the virtual environment with something like poetry env info --path. Once you know that you can "activate it" from anywhere:

. /path/to/venv/bin/activate

Or (in most cases) you can just use any of the executables from that virtual environment directly without having to activate first:

/path/to/venv/bin/python path/to/script.py

Remix from other answers.

poetry shell spawns an environment, but we can also create an environment manualy using the env use command.

# This will create a Python3.7 env 

poetry env use 3.7

Why use env use vs shell?

env use is a pure method that has an output and ends the process. It also activates the environment as required.

So after env completes we can actually use @DaveR's answer and use the run command.

A chained version of this my_bash_script.sh script would be:

#!/bin/bash
# Activate / Create + activate my enviroment
poetry env use 3.7

# Run my script in the above environment
poetry run python3.7 my_script.py

Extra

env command is helpful to see what envs you have activated.

poetry env list
Related