How to manage import paths in Python?

I am new to Python. I am in a company where they built a large Python system. They use a proprietary system to manage paths when the system is running, but now I have been asked to create a stand-alone script that interacts with some of the code on their system. Unfortunately, my stand-alone script will not run under the path they use, so I need to figure out the paths myself.

So for example, I have this line:

from hark.tasks import REPLY_LINE

It is actually copied from some of their older code. In this case, the script may find hark, but hark has a file __init__.py, and that is where the problems begin. So I get the following:

meg/src/python2/hark/hark/__init__.py in <module>()
      5 from flask import jsonify, render_template, request
      6 import jinja2
----> 7 import logbook, logbook.compat
      8 
      9 from healthhark.context import Ghost, g

The project they built actually includes a magazine 3 times. If I do this:

find . -name "*logbook*"

I see:

meg/zurge/opt/python2.7/lib/python2.7/site-packages/logbook
meg/zurge/opt/python2.7-hark/lib/python2.7/site-packages/logbook
meg/zurge/opt/python3.4/lib/python3.4/site-packages/logbook

, , , , , .

Python, , Pythonic , ?

, - pip install, .

+4
1

virtualenv virtualenvwrapper. , , script. .

:

  • .txt,
  • pip virtualenvwrapper
  • source /usr/local/bin/virtualenvwrapper.sh
  • workon hark_task_script_env || ( mkvirtualenv hark_task_script_env && pip install -r requirements.txt )
  • python your-script.py

Virtualenvwrapper . . , .

. proprietry, !

, ( , * nix). script, zsh. , , :

#!/bin/zsh

setopt extended_glob

function find_package_init_files () {
    locate __init__.py
}

# Get the containing folder of a file or a folder
function file_or_folder_to_parent_folder () {
    while read file_or_folder
    do
        echo ${file_or_folder:h}
    done
}

# Exclude folders where the parent folder also has an __init__.py file in it
function exclude_inner_packages () {
    while read init_file_folder
    do
        init_file_parent_folder=${init_file_folder:h}
        if [ ! -e ${init_file_parent_folder}/__init__.py ]
        then
            echo ${init_file_folder}
        fi
    done
}

# This produces an array of all folders
# that contain at least one python package
function get_distinct_python_package_folders () {
    find_package_init_files |
        file_or_folder_to_parent_folder |
        exclude_inner_packages |
        file_or_folder_to_parent_folder |
        sort |
        uniq
}

PYTHONPATH=${(j/:/)$(get_distinct_python_package_folders)} YOUR_SCRIPT_HERE

script, python , , . , , .

, , - .

+1

Source: https://habr.com/ru/post/1569453/


All Articles