[英]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
. 我已经编写了位于
/my/directory/script.py
的脚本script.py
。 This contains many helpful functions that I would like to make available to users of Python on this server. 它包含许多有用的功能,我希望此服务器上的Python用户可以使用。 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. 通常,我会将其打包为一个模块,然后将其移动到
libs
文件夹并以这种方式访问它,但是不幸的是,在我的公司中,当文件放置在那里时,我无法对其进行编辑,因为我没有root访问权限。
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. 我当时想的是在包含
__init__.py
libs
创建一个包含上面导入sys代码的文件夹,并简单地通过导入引用此脚本。 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
在
__init__.py
运行它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.