简体   繁体   中英

Import functions from Python script in remote directory via a custom module

So this problem is a bit convoluted, but I will try to explain. I have written a script script.py that is located in /my/directory/script.py . This contains many helpful functions that I would like to make available to users of Python on this server. Normally, I would package it as a module and move it to the libs folder and access it this way, but unfortunately at my company I am unable to edit files when they are placed there as I will not have root access.

What I have been doing to access this script from either the shell or other scripts is to write:

import sys
sys.path.append('/my/directory')
from script import *

This works, but ideally I would like it to just be:

import script

What I was thinking was making a folder in libs with __init__.py that contains the import sys code above, and simply referencing this script with an import. But when I do this I get an import error that the script is unable to import from my referenced script.

Is there a better way to do this?

Basically I want people to be able to access my module as if it is installed normally by importing a script that imports my functions.

您可以使用pip在本地安装软件包

pip install --user package
import sys
import my.directory.script
sys.modules['script'] = my.directory.script

run this in __init__.py

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