简体   繁体   中英

Python: sys.path.append vs. import?

I have a (single) .py script. In it, I need to import a library.

In order for this library to be found, I need to call 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.

What are good ways to solve this problem?

Clarification after comments:

  • I am using IronPython, and the library path is the path to CPython/lib. This path is (potentially) different on every system.
  • As far as I know, I cannot pass anything via sys.argv, because the script is run in an embedded python interpreter, and there is no main function.

您不应该全局导入,而应该在添加路径后调用的函数内部进行。

Maybe pass the file as an argument using sys.argv, add it to the path and then import it. 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/

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