python can't import module when running a file, but can import the module in interactive shell
Question:
I got a strange problem.
filegetter
is a module developed by someone else and installed with python setup.py install
.
Here is a test file.
#instance.py
import filegetter
when I run
/home/ynx/miniconda3/bin/python /home/ynx/notebook/instance.py
it says:
Traceback (most recent call last):
File "/home/ynx/notebook/instance.py", line 2, in <module>
import filegetter
ModuleNotFoundError: No module named 'filegetter'
But if I run an interactive shell: python
>>> import filegetter
>>>
It works.
I am sure the same python bin is used by check which, why and how can I import it in the file mode?
Answers:
This looks like a problem with sys.path
. When you run the Python shell, the path to the current directory is added to sys.path
, making modules in this directory import
-able. To make a module available to all of your Python programs, store it in the user site directory, which you can find with
$ python -m site --user-site
Alternatively, place a script called usercustomize.py
in the user site directory, which manually adds paths to sys.path
:
import sys
sys.path.append('/path/to')
where the full path of filegetter.py
would be /path/to/filegetter.py
I got a strange problem.
filegetter
is a module developed by someone else and installed with python setup.py install
.
Here is a test file.
#instance.py
import filegetter
when I run
/home/ynx/miniconda3/bin/python /home/ynx/notebook/instance.py
it says:
Traceback (most recent call last):
File "/home/ynx/notebook/instance.py", line 2, in <module>
import filegetter
ModuleNotFoundError: No module named 'filegetter'
But if I run an interactive shell: python
>>> import filegetter
>>>
It works.
I am sure the same python bin is used by check which, why and how can I import it in the file mode?
This looks like a problem with sys.path
. When you run the Python shell, the path to the current directory is added to sys.path
, making modules in this directory import
-able. To make a module available to all of your Python programs, store it in the user site directory, which you can find with
$ python -m site --user-site
Alternatively, place a script called usercustomize.py
in the user site directory, which manually adds paths to sys.path
:
import sys
sys.path.append('/path/to')
where the full path of filegetter.py
would be /path/to/filegetter.py