当前位置: 首页 > news >正文

What Does “Directory of the Script Being Run” Mean?

This is a subtle but crucial detail in understanding how Python resolves imports, especially when you're working with modular code or running scripts from different locations.

🧭 What Does “Directory of the Script Being Run” Mean?

When you execute a Python script like:

python /Users/egonever/DjangoByExamples/mysite/envato/testing/testing4.py"

Python sets the first entry in sys.path to:

/Users/egonever/DjangoByExamples/mysite/envato/testing

This is the directory containing the script, not necessarily the current working directory (CWD) of your shell.

So if testing4.py does:

import helper

Python will look for helper.py in /Users/egonever/DjangoByExamples/mysite/envato/testing — even if your shell is currently in /Users/egonever/DjangoByExamples/mysite

🧪 Example: Script vs CWD

Let’s say you have:

/Users/egonever/DjangoByExamples/mysite/envato/testing'
├── testing4.py
└── helper.py

And you're in /Users/egonever/DjangoByExamples/mysite:

cd /Users/egonever/DjangoByExamples/mysite
python envato/testing/testing4.py

Even though your shell’s CWD is /Users/egonever/DjangoByExamples/mysite
, Python sets sys.path[0] to /Users/egonever/DjangoByExamples/mysite/envato/testing, because that’s where testing4.py lives.

So import helper works.

(venv) egonever@egonevers-MacBook-Air mysite % pwd   
/Users/egonever/DjangoByExamples/mysite
(venv) egonever@egonevers-MacBook-Air mysite % python envato/testing/testing4.py
Inside helper module
os.getcwd()='/Users/egonever/DjangoByExamples/mysite'
sys.path=['/Users/egonever/DjangoByExamples/mysite/envato/testing', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python39.zip', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/egonever/DjangoByExamples/mysite/venv/lib/python3.9/site-packages']
"""testing4.py"""import os, sys
import helperprint(f"{os.getcwd()=}")for k, v in os.environ.items():if k == "PYTHONPATH":print(k, v)print(f"{sys.path=}")
"""helper.py"""
print("Inside helper module")

 

 

 

🧑‍💻 Interactive Mode: CWD Takes Over

Case 1: When CWD is same with the directory where script locates

When you run Python interactively:

cd /Users/egonever/DjangoByExamples/mysite/envato/testing
python

Then sys.path[0] is set to the current working directory — in this case, /Users/egonever/DjangoByExamples/mysite/envato/testing.

So if you type:

import helper

It works because helper.py is in the CWD.

(venv) egonever@egonevers-MacBook-Air testing % pwd
/Users/egonever/DjangoByExamples/mysite/envato/testing
(venv) egonever@egonevers-MacBook-Air testing % python
Python 3.9.6 (default, Mar 12 2025, 20:22:46) 
[Clang 17.0.0 (clang-1700.0.13.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import helper
Inside helper module
>>> import testing4
os.getcwd()='/Users/egonever/DjangoByExamples/mysite/envato/testing'
sys.path=['', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python39.zip', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/egonever/DjangoByExamples/mysite/venv/lib/python3.9/site-packages']
>>> os.listdir()
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'helper', 'testing4']
>>> testing4.__dir__()
['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__file__', '__cached__', '__builtins__', 'os', 'sys', 'helper', 'k', 'v']
>>> import os
>>> os.listdir()
['testing2.py', 'testing3.py', '__init__.py', 'helper.py', 'testing4.py', 'testing.py']
>>> 

Note:

sys.path[0]='', empty string means CWD. 

Case 2: When CWD is different from the directory where script locates

ModuleNotFoundError: No module named 'helper'

(venv) egonever@egonevers-MacBook-Air mysite % pwd
/Users/egonever/DjangoByExamples/mysite
(venv) egonever@egonevers-MacBook-Air mysite % python
Python 3.9.6 (default, Mar 12 2025, 20:22:46) 
[Clang 17.0.0 (clang-1700.0.13.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import helper
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'helper'
>>> from envato.testing import helper
Inside helper module
>>> from envato.testing import testing4
Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/Users/egonever/DjangoByExamples/mysite/envato/testing/testing4.py", line 4, in <module>import helper
ModuleNotFoundError: No module named 'helper'
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'helper']
>>> import sys
>>> sys.path[0]
''
>>> import os
>>> os.getcwd()
'/Users/egonever/DjangoByExamples/mysite'
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'helper', 'os', 'sys']
>>> sys.modules
{'sys': <module 'sys' (built-in)>, 'builtins': <module 'builtins' (built-in)>, '_frozen_importlib': <module 'importlib._bootstrap' (frozen)>, '_imp': <module '_imp' (built-in)>, '_thread': <module '_thread' (built-in)>, '_warnings': <module '_warnings' (built-in)>, '_weakref': <module '_weakref' (built-in)>, '_io': <module 'io' (built-in)>, 'marshal': <module 'marshal' (built-in)>, 'posix': <module 'posix' (built-in)>, '_frozen_importlib_external': <module 'importlib._bootstrap_external' (frozen)>, 'time': <module 'time' (built-in)>, 'zipimport': <module 'zipimport' (frozen)>, '_codecs': <module '_codecs' (built-in)>, 'codecs': <module 'codecs' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/codecs.py'>, 'encodings.aliases': <module 'encodings.aliases' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/encodings/aliases.py'>, 'encodings.cp437': <module 'encodings.cp437' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/encodings/cp437.py'>, 'encodings': <module 'encodings' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/encodings/__init__.py'>, 'encodings.utf_8': <module 'encodings.utf_8' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/encodings/utf_8.py'>, '_signal': <module '_signal' (built-in)>, 'encodings.latin_1': <module 'encodings.latin_1' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/encodings/latin_1.py'>, '_abc': <module '_abc' (built-in)>, 'abc': <module 'abc' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/abc.py'>, 'io': <module 'io' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/io.py'>, '__main__': <module '__main__' (built-in)>, '_stat': <module '_stat' (built-in)>, 'stat': <module 'stat' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/stat.py'>, '_collections_abc': <module '_collections_abc' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/_collections_abc.py'>, 'genericpath': <module 'genericpath' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/genericpath.py'>, 'posixpath': <module 'posixpath' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/posixpath.py'>, 'os.path': <module 'posixpath' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/posixpath.py'>, 'os': <module 'os' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/os.py'>, '_sitebuiltins': <module '_sitebuiltins' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/_sitebuiltins.py'>, '_locale': <module '_locale' (built-in)>, '_bootlocale': <module '_bootlocale' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/_bootlocale.py'>, '_virtualenv': <module '_virtualenv' from '/Users/egonever/DjangoByExamples/mysite/venv/lib/python3.9/site-packages/_virtualenv.py'>, '_distutils_hack': <module '_distutils_hack' from '/Users/egonever/DjangoByExamples/mysite/venv/lib/python3.9/site-packages/_distutils_hack/__init__.py'>, 'types': <module 'types' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/types.py'>, 'importlib._bootstrap': <module 'importlib._bootstrap' (frozen)>, 'importlib._bootstrap_external': <module 'importlib._bootstrap_external' (frozen)>, 'warnings': <module 'warnings' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/warnings.py'>, 'importlib': <module 'importlib' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py'>, 'importlib.machinery': <module 'importlib.machinery' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/machinery.py'>, '_heapq': <module '_heapq' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/lib-dynload/_heapq.cpython-39-darwin.so'>, 'heapq': <module 'heapq' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/heapq.py'>, 'itertools': <module 'itertools' (built-in)>, 'keyword': <module 'keyword' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/keyword.py'>, '_operator': <module '_operator' (built-in)>, 'operator': <module 'operator' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/operator.py'>, 'reprlib': <module 'reprlib' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/reprlib.py'>, '_collections': <module '_collections' (built-in)>, 'collections': <module 'collections' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/collections/__init__.py'>, 'collections.abc': <module 'collections.abc' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/collections/abc.py'>, '_functools': <module '_functools' (built-in)>, 'functools': <module 'functools' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/functools.py'>, 'contextlib': <module 'contextlib' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/contextlib.py'>, 'enum': <module 'enum' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/enum.py'>, '_sre': <module '_sre' (built-in)>, 'sre_constants': <module 'sre_constants' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/sre_constants.py'>, 'sre_parse': <module 'sre_parse' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/sre_parse.py'>, 'sre_compile': <module 'sre_compile' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/sre_compile.py'>, 'copyreg': <module 'copyreg' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/copyreg.py'>, 're': <module 're' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/re.py'>, 'typing.io': <class 'typing.io'>, 'typing.re': <class 'typing.re'>, 'typing': <module 'typing' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/typing.py'>, 'importlib.abc': <module 'importlib.abc' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/abc.py'>, 'importlib.util': <module 'importlib.util' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/util.py'>, 'zope': <module 'zope' (namespace)>, 'site': <module 'site' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/site.py'>, 'readline': <module 'readline' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/lib-dynload/readline.cpython-39-darwin.so'>, 'atexit': <module 'atexit' (built-in)>, 'rlcompleter': <module 'rlcompleter' from '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/rlcompleter.py'>, 'envato': <module 'envato' from '/Users/egonever/DjangoByExamples/mysite/envato/__init__.py'>, 'envato.testing': <module 'envato.testing' from '/Users/egonever/DjangoByExamples/mysite/envato/testing/__init__.py'>, 'envato.testing.helper': <module 'envato.testing.helper' from '/Users/egonever/DjangoByExamples/mysite/envato/testing/helper.py'>}
>>> 

 

 

🧪 REPL vs Script Behavior

Modesys.path[0] is...Example
Script executionDirectory of the scriptpython /path/to/script.py
Interactive shellCurrent working directory (CWD)python from /some/dir
python -mDirectory of the module’s parent packagepython -m package.module

🧠 Why This Matters

  • If you run a script from outside its directory, relative imports might fail unless the script’s location is in sys.path.

  • This is why tools like PYTHONPATH, sys.path.append(...), or using python -m are often needed in modular projects.

http://www.lryc.cn/news/596696.html

相关文章:

  • final修饰符不可变的底层
  • SpringBoot PO VO BO POJO实战指南
  • Pycharm下载、安装及配置
  • 力扣 hot100 Day52
  • RabbitMQ03——面试题
  • 为什么要微调大语言模型
  • 论文笔记 | Beyond Pick-and-Place: Tackling Robotic Stacking of Diverse Shapes
  • 解决pip指令超时问题
  • 数据结构 堆(2)---堆的实现
  • LeetCode 热题100:42.接雨水
  • Unity UI的未来之路:从UGUI到UI Toolkit的架构演进与特性剖析(1)
  • 业务流逻辑如何搭建?为何橙武平台选用了 LogicFlow?​
  • day19 链表
  • 程序是如何生成的-以c语言为例
  • 信息学奥赛一本通 1553:【例 2】暗的连锁
  • 前端_CSS复习
  • 【React 入门系列】React 组件通讯与生命周期详解
  • 高可用架构模式——数据集群和数据分区
  • 单细胞转录组学+空间转录组的整合及思路
  • OneCode3.0 UI组件注解详解手册
  • 【vscode】vscode中python虚拟环境的创建
  • 回调地狱及解决方法
  • error C++17 or later compatible compiler is required to use ATen.
  • 【coze扣子】第1篇:coze快速入门
  • 威胁情报:Solana 开源机器人盗币分析
  • 以Java程序员角度理解MCP
  • 学习游戏制作记录(战斗系统简述以及击中效果)7.22
  • [c++11]std::function/bind
  • 基于SpringBoot+Vue的班级管理系统(Echarts图形化分析)
  • 101.对称二叉树