从 virtualenv bin 中运行 python 脚本不起作用 [英] Running python script from inside virtualenv bin is not working

查看:34
本文介绍了从 virtualenv bin 中运行 python 脚本不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,希望在全球范围内可用.我从标准的 hashbang 开始:

I have a script I want to be available globally. I've started it with the standard hashbang:

#! /usr/bin/env python

并将其链接到我的 virtualenv 的 bin 目录中:

And linked it into the bin directory of my virtualenv:

~/environments/project/env/bin/myscript

并将该目录添加到我的路径中.当我运行命令时:

And added that directory to my path. When I run the command:

myscript

我在其中一个库中遇到导入错误.但是,如果我激活虚拟环境并运行脚本,它会按预期工作.

I get an import error with one of the libraries. However, if I activate the virtual environment and run the script, it works as expected.

我已经排除了符号链接的问题(我也尝试将脚本移到 bin 文件夹中).我也试过用 python 运行脚本

I've ruled out a problem with the symlink (I've also tried just moving the script inside the bin folder). I've also tried running the script with python

python ~/environments/project/env/bin/myscript

以前我使用一个脚本来激活环境然后运行我的脚本,但我的印象是从这个文件夹运行的脚本应该与 virtualenv 的解释器和站点包一起运行.关于为什么这可能不起作用的任何想法或我可以调试它的某些方法?

Previously I was using a script that activated the environment and then ran my script, but I was under the impression that script run from this folder should run with the virtualenv's interpretor and site-packages. Any ideas of why this might not be working or some ways I could debug this?

推荐答案

将脚本放入您的 virtualenv 的 bin,然后将该 bin 位置添加到您的全局 PATH 将不会自动获取您的 virtualenv.您确实需要先获取它以使其处于活动状态.

Putting the script into the bin of your virtualenv, and then adding that bin location to your global PATH will not automatically source your virtualenv. You do need to source it first to make it active.

您的系统所知道的只是检查可执行文件的额外路径并运行它.该脚本中没有任何内容指示 virtualenv.

All that your system knows is to check that extra path for the executable and run it. There isn't anything in that script indicating a virtualenv.

但是,您可以将 she-bang 行硬编码到您的 virtualenv python,在这种情况下,站点包将在路径上结束:

You could, however, hardcode the she-bang line to your virtualenv python, in which case the site-packages will end up on the path:

#!/Users/foo/environments/project/env/bin/python

或者另一种选择是简单地创建一个小的 bash 包装器来调用您的原始 pythons 脚本,这将允许您使用通用的she-bang 保留原始脚本..

Or another option is to simply create a tiny bash wrapper that calls your original pythons script, which will allow you to leave your original script with a generic she-bang..

所以如果 myscript.py 是:#!/usr/bin/env python ...

So if myscript.py is: #!/usr/bin/env python ...

然后你可以制作一个 myscript :

Then you can make a myscript :

#!/bin/bash

/Users/foo/environments/project/env/bin/python myscript.py

当您执行 myscript 时,它会使用您设置的解释器显式调用您的 Python 脚本.

When you do myscript, it will explicitly call your python script with the interpreter you set up.

这篇关于从 virtualenv bin 中运行 python 脚本不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆