简体   繁体   中英

How to add a PYTHONPATH in a virtual environment with brew on a Mac?

I am running macOS Mojave and I have installed Python 3.7 following this blog post here .

In short, what I did:

  1. Installed Xcode
  2. Set up Homebrew
  3. Installed Python 3
  4. Created a virtual environment

All following the steps in the article.

I now created a python file with some functions. I know that to use this file in a jupyter notebook as import my_file , I need to have the path to this file added in a PYTHONPATH usually done in the .bash_profile . Even though I did added export PYTHONPATH="/path/to/my/files/folder/:$PYTHONPATH" , nothing happened.

My question is: How can I add a custom PYTHONPATH, so that I can import the file in jupyter or ipython ?

你忘记了美元

export PYTHONPATH=$PYTHONPATH:/your/path/to/your/module

I have the same env too you, and there are some ways to solve it.

First , you can edit the sys.path using the sys.path.append() --Not recommended

import sys

import sys.path.append('/your/work/path')

Second , you can edit PYTHONPATH in "~/.bash_profile", but it will not work when you use the IDEA, such as Pycharm.

export PYTHONPATH=$PYTHONPATH:/your/work/path

source ~/.bash_profile

Last ,you can just copy your work directory to dist-packages which you can find it using sys.path .

Also, you can find some other ways from Add to python path mac os x

In my installation, /usr/local/bin/ipython was a script containing

#!/bin/bash
PYTHONPATH="/usr/local/Cellar/ipython/6.5.0/libexec/lib/python3.7/site-packages:/usr/local/Cellar/ipython/6.5.0/libexec/vendor/lib/python3.7/site-packages" exec "/usr/local/Cellar/ipython/6.5.0/libexec/bin/ipython" "$@"`.

Changing this to

#!/bin/bash
PYTHONPATH=$PYTHONPATH:"/usr/local/Cellar/ipython/6.5.0/libexec/lib/python3.7/site-packages:/usr/local/Cellar/ipython/6.5.0/libexec/vendor/lib/python3.7/site-packages" exec "/usr/local/Cellar/ipython/6.5.0/libexec/bin/ipython" "$@"

did the trick for me.

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