python - 创建将在指定 python 虚拟环境中运行的 .py 文件,同时还通过指定路径导入其他文件

标签 python linux module virtualenv

总的来说,我对 Linux 还很陌生,一直负责管理服务器。 由于一些原因,我不得不在我的用户下创建一个python虚拟环境。

这样的文件目录:

~
    /python_venv
    /scripts
        /data_curation
            -master.py
            /mods
               -file1.py
               -file2.py
            /other
               -file3.py
        /otherscripts
            -file4.py

^基本上 python venv 在 ~ 目录中。 其他所有内容都位于 scripts/data_curation 中 和脚本/其他脚本。

我对两件事很好奇。 1) 有没有一种方法可以从命令行运行每个文件而无需手动激活 python venv?例如,在 .py 文件中放一行,通过指定路径自行调用 venv?

2) 确保这些文件中的每一个都可以相互访问的最简单方法是什么?意思是如果我想将 file3.py 导入 file4.py,我该怎么做?

我一直在尝试使用 importlib,但出现此错误:

(python) [user@server]$ python scripts/data_curation/mods/file1.py
scripts/data_curation/device_functions/epon_nokia.py
ModuleSpec(name='file3', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f66399f9a90>, origin='scripts/data_curation/other/file3.py')
__init__.py
scripts/data_curation/other/__init__.py
ModuleSpec(name='__init__', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f661a7242b0>, origin='scripts/data_curation/other/__init__.py')
__pycache__
scripts/data_curation/other/__pycache__
Traceback (most recent call last):
  File "scripts/data_curation/file1.py", line 21, in <module>
    module = imputil.module_from_spec(spec)
  File "<frozen importlib._bootstrap>", line 568, in module_from_spec
AttributeError: 'NoneType' object has no attribute 'loader'

最佳答案

对于第一个问题,您可以在您的 venv 中显式引用 Python 可执行文件:

python_venv/bin/python scripts/data/master.py

或者将每个脚本开头的 shebang 更改为直接指向同一个位置,然后仅使用 scripts/data/master.py 运行(尽管这对位置进行了硬编码,您可以可能不想要)。

关于python - 创建将在指定 python 虚拟环境中运行的 .py 文件,同时还通过指定路径导入其他文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55385789/

相关文章:

javascript - typescript 库: Hide internal exports

python - apt-get purge 做了什么?

python - 添加和删​​除具有一对多关系的行的问题

python - 如何将图像添加到 Pythonista 的 ui 设计器

linux - 使用 'screen' 从 GVIM 分离

angular - Uncaught ReferenceError : ace is not defined in angular 4

Python 字典吃掉了 ram

java - java 的 fileWriter() 函数是否适用于 Linux 类型的机器?

linux - 命令面板中缺少 "Shell Command: Install"命令 - VS 代码 - ubuntu

android - 多个模块项目中的每个 AndroidManifest 可以有自己的 <application> 部分吗?模块之间如何共享资源?