2

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.
3
  • Is the library not stored with your Python install (in site-packages)? Commented Apr 25, 2013 at 15:05
  • 1
    Would it not be simpler to set the PYTHONPATH environment variable instead of changing sys.path? Commented Apr 25, 2013 at 15:09
  • I am using IronPython, and need to use CPython packages; the path I want to append is actually the path to the CPython lib dir. So no. Commented Apr 25, 2013 at 15:10

2 Answers 2

3

You should not do the import globally, but inside a function which gets called after you appended the path.

Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.