Reputation: 1765
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.
Upvotes: 2
Views: 50
Reputation: 82889
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__)))
Upvotes: 2