[英]Python: sys.path.append vs. import?
I have a (single) .py script. 我有一个(单一).py脚本。 In it, I need to import a library.
在其中,我需要导入一个库。
In order for this library to be found, I need to call sys.path.append. 为了找到该库,我需要调用sys.path.append。 However, I do not want to hardcode the path to the library, but pass it as a parameter.
但是,我不想对路径进行硬编码,而是将其作为参数传递。
So my problem is that if I make a function (set_path) in this file, I need to import the file, and import fails because the path is not yet appended. 所以我的问题是,如果我在此文件中创建一个函数(set_path),则需要导入该文件,并且导入失败,因为该路径尚未附加。
What are good ways to solve this problem? 有什么好的方法可以解决这个问题?
Clarification after comments: 评论后澄清:
您不应该全局导入,而应该在添加路径后调用的函数内部进行。
Maybe pass the file as an argument using sys.argv, add it to the path and then import it. 也许使用sys.argv将文件作为参数传递,将其添加到路径,然后导入。 Then run your program like this:
然后像这样运行程序:
python my_program.py somefolder/some_import.py
Here's a reference for using sys.argv: http://www.pythonforbeginners.com/systems-programming/python-sys-argv/ 这是使用sys.argv的参考: http ://www.pythonforbeginners.com/systems-programming/python-sys-argv/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.