python - How to import some variable in another script without using sys?
问题描述
When I try to do using sys in following way, it gives error: name 'path' is not defined
.
Here test.py
is file in folder directory. Also folder directory has __init__.py
in it.
import sys
sys.path.append('c/Users/Downloads/folder')
from test import *
print(path)
Content of test.py
path="sample"
I also tried writing from test import path
but it did not work. So is there any other way than sys
. I am not able to find why it's not working with it, since most answers recommend this.
EDIT: Python is used a lot in industry so I am hopeful there must be some way for that (without using or using sys). I can have multiple files with same name in my system so help provided in answer and comments are not permanent fix.
解决方案
这是一个有趣的问题,所以我花了一点时间进行调查。经过一番挖掘,事实证明问题是在 sys.path 目录之一中已经有另一个名为“test.py”的脚本,而 Python 正在导入该脚本而不是您想要的脚本。
当你导入一个模块时,Python 会按照它们列出的顺序在每个搜索路径中查找它sys.path
并导入第一个匹配项。使用sys.path.append('path/to/folder')
失败,因为它将搜索路径添加到列表末尾,并且 Python 已经test.py
在它之前列出的目录之一中找到了匹配项。这也是sys.path.insert(0,'path/to/folder')
有效的原因——因为它在列表的前面插入了指定的路径,所以 Python 会首先找到它。
使固定
将文件“test.py”的名称更改为与任何其他文件名都不匹配的唯一名称。这可能是最好的方法。
您可以使用
sys.path.insert(0,'path/to/folder')
将指定路径放在搜索路径列表中的第一个位置。另一种方法是遍历 sys.path 列表中的每个目录并删除或重命名其他“test.py”文件。不建议
除了 sys 还有其他方法吗
如果您正在运行的脚本和要导入的脚本都在同一个文件夹中,则不需要sys
module.
如果文件在不同的文件夹中并且您绝对不会使用sys
,那么您可以PYTHONPATH
在运行脚本之前在终端中进行设置。请注意,您必须在同一个 shell 中运行 python 脚本才能使其工作。此外,如果您的脚本所在的文件夹还包含一个与您要从另一个文件夹导入的文件同名的文件,这将不起作用
Linux 重击:
export PYTHONPATH="path/to/folder/"
Windows Powershell:
set PYTHONPATH="path/to/folder/"
推荐阅读
- android - keyListener 无法识别输入
- javascript - SublimeREPL 不适用于 Javascript 代码
- if-statement - IF 的参数数量错误
- node.js - mongoose.populate() 返回一个空数组
- python - 在 Keras 上将两个模型的权重加载到一个中
- python-3.x - 如何正确绘制小浮点数
- swift - 单击按钮后如何更改变量 UITextView?
- javascript - 做出反应。如何将 arg 传递给 onClick 调用的函数而不自动触发它
- sql - SQL 语句中的 IN 运算符不起作用?
- request - Cheerio 在 Google Cloud 功能中未按预期工作