[英]conda and python shell scripts
Suppose I have a python shell script of the usual shebang kind (let's suppose it's in a file called foo.py
: 假设我有一个通常的shebang类型的python shell脚本(让我们假设它在一个名为foo.py
的文件中:
#!/usr/bin/env python
print("Hello World")
with the twist that I need to run it in a given python environment Now, of course, I can write a script of the following kind: 我需要在给定的python环境中运行它的扭曲现在,当然,我可以编写以下类型的脚本:
#!/bin/sh
conda activate myenv
exec foo.py
But this is mildly unsatisfying aesthetically. 但这在美学上有点令人不满意。 Is there a way to package the environment into the script to avoid the extra level of scripting? 有没有办法将环境打包到脚本中以避免额外的脚本级别?
Option 1: explicit interpreter path 选项1:显式解释器路径
You can explicitly find the path to the python interpreter in your environment and use that in the shebang: 您可以在您的环境中显式找到python解释器的路径,并在shebang中使用它:
source activate myenv
which python
Will output something like /Users/me/anaconda/envs/myenv/bin/python
. 输出类似于/Users/me/anaconda/envs/myenv/bin/python
。 You can then write the python script's shebang using that full path: 然后,您可以使用完整路径编写python脚本的shebang:
#!/Users/me/anaconda/envs/myenv/bin/python
...
However, it's still kinda ugly. 但是,它仍然有点难看。
Option 2: symlinks 选项2:符号链接
#!/usr/bin/env python
just looks through $PATH
for something called " python
" and uses that to run the script. #!/usr/bin/env python
只是通过$PATH
查找名为“ python
”的东西并使用它来运行脚本。 We can use this behavior to get nicer shebangs for our conda environments. 我们可以使用此行为为我们的conda环境获得更好的shebang。
Here's a script to add symlinks in ~/bin
for each conda environment: 这是一个在~/bin
为每个conda环境添加符号链接的脚本:
#!/usr/bin/env bash
conda_prefix="$HOME/anaconda" # Modify this line if your anaconda folder is somewhere else
mkdir -p "$HOME/bin" # Make ~/bin if it doesn't exist
for env_dir in "$conda_prefix/envs/"*; do
env_name=$(basename "$env_dir")
ln -s "$env_dir/bin/python" "$HOME/bin/$env_name"
echo "Made symlink for environment $env_name"
done
Once you've run that once (and you've added $HOME/bin
to your $PATH
in .profile
), you can reference conda envs directly in the shebang: 一旦你运行了一次(并且你已经将$HOME/bin
添加到 .profile
的$PATH
),你可以直接在shebang中引用conda envs:
#!/usr/bin/env myenv
...
This will find myenv
in the $PATH
as $HOME/bin/myenv
, which is a symlink to $HOME/anaconda/envs/myenv/bin/python
thanks to our script above. 这将在$PATH
找到myenv
作为$HOME/bin/myenv
,这是$HOME/anaconda/envs/myenv/bin/python
的符号链接,这要归功于我们上面的脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.