0

This is my file.py:

import os
os.chdir('/home/python3.10')
print(os.getcwd())
print(os.system('pwd; ls'))
import template
print(template.text)

I have a virtual environment in /home/python3.10.

If I run file like this:

/home/python3.10/venv/bin/python3.10 /home/another_dir/file.py

I get this error:

/home/python3.10
/home/python3.10
__pycache__  file1.txt  requirements.txt  template.py  test.py  venv
0
Traceback (most recent call last):
  File "/home/another_dir/file.py", line 5, in <module>
    import template
ModuleNotFoundError: No module named 'template'

But if I run /home/python3.10/venv/bin/python3.10 in the shell, then I run all of above lines, it works:

Python 3.10.13 (main, Aug 25 2023, 13:20:03) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> os.chdir('/home/python3.10')
>>> print(os.getcwd())
/home/python3.10
>>> print(os.system('pwd; ls'))
/home/python3.10
__pycache__  file1.txt  requirements.txt  template.py  test.py  venv
0
>>> import template
>>> print(template.text)
{text}

What's the reason I have this error? I see the getcwd() is the correct directory, but I'm not sure why it cannot see template.py to import as module.

2
  • 1
    Generally, your modules should be kept in a fixed location independent of your script location. Make your code installable, so that template.py gets installed to your virtual environment's lib/site-packages directory, and your script gets install to your virtual environment's bin directory. Commented Feb 19, 2024 at 3:05
  • @chepner I add this command to the crontab, and PATH=/root when running behind the crontab. So, I need to tell where the path so template.py is. Do you have any idea for this? Commented Feb 19, 2024 at 17:45

1 Answer 1

1

When you run python interactively, the default module import path is the current directory. If you call os.chdir() to change the current directory, the default module import path is also updated.

But when you run a python script like this:

python /some/dir/myscript.py

The default module import path is /some/dir, and it does not change, even if you change the current directory with os.chdir().

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

3 Comments

Thanks, I understood completely. Then what's the solution? I mean any other solutions than cd /home/correct-path; /home/python3.10/venv/bin/python3.10 /home/another/filepy.
I did what stackoverflow.com/a/24722419/5790653 and it's solved in my case.
I add this command to the crontab, and PATH=/root when running behind the crontab. So, I need to tell where the path so template.py is. Do you have any idea for this? What I said in the previous comment was just a workaround in this case:(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.