2

I have two files, say main.py and foo.py. When I import foo in main, I thought the lines in foo.py that not in a function automaticly run.

But when I add an executable to PATH in foo, and call main of foo that involves that executable which should be in PATH, it gives an error: geckodriver executable must be in PATH. If I add it to PATH right after the imports in main.py, it works correctly. Here are the sample codes:

main.py:

# some imports
from foo_file import foo

foo.main()

foo.py:

import os

FILENAME = os.path.dirname(os.path.abspath(__file__))

os.environ["PATH"] += os.pathsep + os.path.join(FILENAME, "assets")

def main():
    # some work involves selenium

Why the first try doesn't work and gives the error? Thanks.

0

1 Answer 1

2

This is kind of a wild guess, but since you are importing foo as

from foo_file import foo

I assume that foo is in a sub-directory, i.e. something like

+- main.py
\- foo_file
   \- foo.py

Thus, when you add os.path.abspath(__file__) to PATH, it will add the path of the subdirectory, not of the directory containing the main.py, which is probably the directory that contains the assets folder, since you said that it works fine if the PATH-adding code is directly in main.

You can easily check (a) that and when the code is executed, and (b) which path is retrieved, if you add an accordant print line in both the foo.py and main.py files, e.g.

print(__file__, os.path.dirname(os.path.abspath(__file__)))
Sign up to request clarification or add additional context in comments.

2 Comments

Aw yess, you absolutely correct, how I didn't see that. Thanks, I will try it asap.
Do you know how can I get the path of assets from foo in a good way?

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.