简体   繁体   中英

Run command after spawning Poetry Shell

我使用 Python Poetry,需要自动化这个过程。具体来说,每次我需要去一个目录

cd /work/directory

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM