site --- قلاب پیکربندی مختص سایت¶
کد منبع: Lib/site.py
این ماژول در حین راهاندازی بهطور خودکار ایمپورت میشود. میتوان با استفاده از گزینهی -S مفسر، از ایمپورت خودکار جلوگیری کرد.
Importing this module normally appends site-specific paths to the module search path
and adds callables, including help() to the built-in
namespace. However, Python startup option -S blocks this, and this module
can be safely imported with no automatic modifications to the module search path
or additions to the builtins. To explicitly trigger the usual site-specific
additions, call the main() function.
تغییر یافته در نسخهی 3.3: ایمپورت کردن ماژول، پیشتر حتی در صورت استفاده از -S نیز باعث دستکاری مسیرها میشد.
این کار با ساختن حداکثر چهار پوشه از یک بخش سر و یک بخش دم آغاز میشود. برای بخش سر، از sys.prefix و sys.exec_prefix استفاده میکند؛ بخشهای سر خالی نادیده گرفته میشوند. برای بخش دم، از رشته خالی و سپس lib/site-packages (در ویندوز) یا lib/pythonX.Y[t]/site-packages (در یونیکس و macOS) استفاده میکند. (پسوند اختیاری "t" نشاندهندهی free-threaded build است و در صورتی اضافه میشود که "t" در ثابت sys.abiflags وجود داشته باشد.) برای هر یک از ترکیبهای متمایز سر و دم، بررسی میکند که آیا آن ترکیب به یک پوشه موجود اشاره دارد یا خیر، و در این صورت، آن را به sys.path اضافه میکند و همچنین مسیر تازه اضافهشده را برای پروندههای پیکربندی بررسی میکند.
تغییر یافته در نسخهی 3.5: پشتیبانی از پوشهی «site-python» حذف شده است.
تغییر یافته در نسخهی 3.13: در یونیکس، نصبهای پایتون نخآزاد با پسوند «t» در نام پوشهی مختص نسخه شناسایی میشوند، مانند lib/python3.13t/.
تغییر یافته در نسخهی 3.14: site دیگر مسئول بهروزرسانی sys.prefix و sys.exec_prefix در محیطهای مجازی نیست. این کار اکنون در حین مقداردهی اولیه مسیر انجام میشود. در نتیجه، در محیطهای مجازی، sys.prefix و sys.exec_prefix دیگر به مقداردهی اولیه site وابسته نیستند و بنابراین تحت تأثیر -S قرار نمیگیرند.
When running under a virtual environment,
the pyvenv.cfg file in sys.prefix is checked for site-specific
configurations. If the include-system-site-packages key exists and is set to
true (case-insensitive), the system-level prefixes will be searched for
site-packages, otherwise they won't. If the system-level prefixes are not searched then
the user site prefixes are also implicitly not searched for site-packages.
The site module recognizes two startup configuration files of the form
name.pth for path configurations, and name.start for
pre-first-line code execution. Both files can exist in one of the four
directories mentioned above. Within each directory, these files are sorted
alphabetically by filename, then parsed in sorted order.
Path extensions (.pth files)¶
name.pth contains additional items (one per line) to be appended to
sys.path. Items that name non-existing directories are never added to
sys.path, and no check is made that the item refers to a directory rather
than a file. No item is added to sys.path more than once. Blank lines
and lines beginning with # are skipped.
For backward compatibility, lines starting with import (followed by space
or tab) are executed with exec().
تغییر یافته در نسخهی 3.13: پروندههای .pth اکنون ابتدا با UTF-8 کدگشایی میشوند و در صورت شکست، با locale encoding کدگشایی میشوند.
تغییر یافته در نسخهی 3.15: .pth file lines starting with import are deprecated. During
the deprecation period, such lines are still executed (except in the case
below), but a diagnostic message is emitted only when the -v flag
is given.
import lines in name.pth are silently ignored when a
matching name.start file exists.
Errors on individual lines no longer abort processing of the rest of the file. Each error is reported and the remaining lines continue to be processed.
منسوخ شده از نسخهی 3.15, در نسخهی 3.20 حذف خواهد شد: Decoding name.pth files in any encoding other than utf-8-sig
is deprecated in Python 3.15, and support for decoding from the locale
encoding will be removed in Python 3.20.
import lines in name.pth files are deprecated and will be
silently ignored in Python 3.18 and 3.19. In Python 3.20 a warning will be
produced for import lines in name.pth files.
Startup entry points (.start files)¶
اضافه شده در نسخهی 3.15.
A startup entry point file is a file whose name has the form
name.start and exists in one of the site-packages directories
described above. Each file specifies entry points to be called during
interpreter startup, using the pkg.mod:callable syntax understood by
pkgutil.resolve_name().
Each non-blank line that does not begin with # must contain an entry
point reference in the form pkg.mod:callable. The colon and callable
portion are mandatory. Each callable is invoked with no arguments, and
any return value is discarded.
.start files are processed after all .pth path extensions
have been applied to sys.path, ensuring that paths are available
before any startup code runs.
Unlike sys.path extensions from .pth files, duplicate entry
points are not de-duplicated --- if an entry point appears more than once,
it will be called more than once.
If an exception occurs during resolution or invocation of an entry point,
a traceback is printed to sys.stderr and processing continues with
the remaining entry points.
.start files must be encoded in UTF-8.
PEP 829 defined the original specification for these features.
توجه
If a name.start file exists alongside a name.pth file
with the same base name, any import lines in the .pth file are
ignored in favor of the entry points in the .start file.
توجه
Executable lines (import lines in name.pth files and
name.start file entry points) are always run at Python startup
(unless -S is given to disable the site.py module entirely),
regardless of whether a particular module is actually going to be used.
توجه
name.start files invoke pkgutil.resolve_name() with
strict=True, which requires the full pkg.mod:callable form.
Startup file examples¶
For example, suppose sys.prefix and sys.exec_prefix are set to
/usr/local. The Python X.Y library is then installed in
/usr/local/lib/pythonX.Y. Suppose this has
a subdirectory /usr/local/lib/pythonX.Y/site-packages with three
sub-subdirectories, foo, bar and spam, and two path
configuration files, foo.pth and bar.pth. Assume
foo.pth contains the following:
# foo package configuration
foo
bar
bletch
و bar.pth شامل موارد زیر است:
# bar package configuration
bar
سپس پوشههای مختص نسخه زیر به sys.path اضافه میشوند، به این ترتیب:
/usr/local/lib/pythonX.Y/site-packages/bar
/usr/local/lib/pythonX.Y/site-packages/foo
توجه داشته باشید که bletch کنار گذاشته شده است، زیرا وجود ندارد؛ پوشهی bar پیش از پوشهی foo قرار میگیرد، زیرا bar.pth از نظر الفبایی پیش از foo.pth میآید؛ و spam کنار گذاشته شده است، زیرا در هیچکدام از پروندههای پیکربندی مسیر ذکر نشده است.
Let's say that there is also a foo.start file containing the
following:
# foo package startup code
foo.submod:initialize
Now, after sys.path has been extended as above, and before Python turns
control over to user code, the foo.submod module is imported and the
initialize() function from that module is called.
Migrating from import lines in .pth files to .start files¶
If your package currently ships a name.pth file, you can keep all
sys.path extension lines unchanged. Only import lines need to be
migrated.
To migrate, create a callable (taking zero arguments) within an importable
module in your package. Reference it as a pkg.mod:callable entry point
in a matching name.start file. Move everything on your import
line after the first semi-colon into the callable() function.
If your package must straddle older Pythons that do not support PEP 829
and newer Pythons that do, change the import lines in your
name.pth to use the following form:
import pkg.mod; pkg.mod.callable()
Older Pythons will execute these import lines, while newer Pythons will
ignore them in favor of the name.start file. After the straddling
period, remove all import lines from your .pth files.
sitecustomize¶
پس از این دستکاریهای مسیر، تلاش میشود ماژولی به نام sitecustomize ایمپورت شود که میتواند سفارشیسازیهای دلخواه و مختص سایت را انجام دهد. این ماژول معمولاً توسط مدیر سیستم در پوشهی site-packages ایجاد میشود. اگر این ایمپورت با ImportError یا استثنایی از زیرکلاسهای آن ناموفق باشد و ویژگی name آن استثنا برابر 'sitecustomize' باشد، بهصورت خاموش نادیده گرفته میشود. اگر پایتون بدون در دسترس بودن جریانهای خروجی شروع شود، مانند pythonw.exe در ویندوز (که بهطور پیشفرض برای راهاندازی IDLE استفاده میشود)، هرگونه تلاش برای خروجی از sitecustomize نادیده گرفته میشود. هر استثنای دیگری باعث شکستی خاموش و شاید مرموز در فرایند میشود.
usercustomize¶
پس از این، اگر ENABLE_USER_SITE درست باشد، تلاش میشود ماژولی به نام usercustomize، که میتواند سفارشیسازیهای دلخواه و مختص کاربر را انجام دهد، ایمپورت شود. این پرونده قرار است در پوشهی site-packages کاربر (در زیر ببینید) ایجاد شود؛ این پوشه بخشی از sys.path است، مگر آنکه با -s غیرفعال شده باشد. اگر این ایمپورت با استثنای ImportError یا استثنایی از زیرکلاس آن شکست بخورد و ویژگی name آن استثنا برابر 'usercustomize' باشد، بهصورت خاموش نادیده گرفته میشود.
توجه داشته باشید که در برخی سیستمهای غیر Unix، sys.prefix و sys.exec_prefix خالی هستند و دستکاریهای مسیر نادیده گرفته میشوند؛ با این حال، همچنان تلاش برای ایمپورت sitecustomize و usercustomize انجام میشود.
پیکربندی Readline¶
در سیستمهایی که از readline پشتیبانی میکنند، اگر پایتون در حالت تعاملی و بدون گزینه -S شروع شده باشد، این ماژول همچنین ماژول rlcompleter را نیز ایمپورت و پیکربندی میکند. رفتار پیشفرض، فعالسازی تکمیل با کلید Tab و استفاده از ~/.python_history بهعنوان پرونده ذخیره تاریخچه است. برای غیرفعالسازی آن، ویژگی sys.__interactivehook__ را در ماژول sitecustomize یا usercustomize خود یا پرونده PYTHONSTARTUP خود حذف (یا بازنویسی) کنید.
تغییر یافته در نسخهی 3.4: فعالسازی rlcompleter و تاریخچه بهصورت خودکار انجام شد.
محتویات ماژول¶
- site.PREFIXES¶
فهرستی از پیشوندها برای پوشههای site-packages.
- site.ENABLE_USER_SITE¶
پرچمی که وضعیت پوشهی site-packages کاربر را نشان میدهد.
Trueیعنی این پوشه فعال است و بهsys.pathافزوده شده است.Falseیعنی به درخواست کاربر (با-sیاPYTHONNOUSERSITE) غیرفعال شده است.Noneیعنی به دلایل امنیتی (عدم تطابق شناسهی کاربر یا گروه با شناسهی مؤثر) یا توسط مدیر غیرفعال شده است.
- site.USER_SITE¶
مسیر site-packages کاربر برای پایتون در حال اجرا. اگر
getusersitepackages()هنوز فراخوانی نشده باشد، ممکن استNoneباشد. مقدار پیشفرض برای UNIX و ساختهای غیرچارچوب macOS برابر با~/.local/lib/pythonX.Y[t]/site-packages، برای ساختهای چارچوب macOS برابر با~/Library/Python/X.Y/lib/python/site-packages، و در ویندوز%APPDATA%\Python\PythonXY\site-packagesاست. نویسه اختیاری «t» نشاندهنده ساخت نخآزاداست. این پوشه یک پوشه سایت (site directory) است، به این معنا که پروندههای.pthدرون آن پردازش خواهند شد.
- site.USER_BASE¶
مسیر پوشهی پایه برای site-packages کاربر. اگر
getuserbase()هنوز فراخوانی نشده باشد، ممکن استNoneباشد. مقدار پیشفرض برای ساختهای غیرچارچوبی در UNIX و macOS برابر~/.local، برای ساختهای چارچوبی در macOS برابر~/Library/Python/X.Y، و برای Windows برابر%APPDATA%\Pythonاست. این مقدار برای محاسبهی پوشههای نصب اسکریپتها، پروندههای داده، ماژولهای پایتون و غیره برای طرحواره نصب کاربر استفاده میشود. همچنینPYTHONUSERBASEرا ببینید.
- site.main()¶
همهی پوشههای استانداردِ خاصِ سایت را به مسیر جستجوی ماژول اضافه میکند. این تابع بهصورت خودکار هنگامی که این ماژول ایمپورت میشود فراخوانی میشود، مگر اینکه مفسر پایتون با پرچم
-Sراهاندازی شده باشد.تغییر یافته در نسخهی 3.3: این تابع پیشتر بهطور غیرشرطی فراخوانی میشد.
- site.makepath(*paths)¶
Join paths with
os.path.join(), attempt to make the result absolute withos.path.abspath(), and return a 2-tuple containing the absolute path and its case-normalized form as produced byos.path.normcase(). Ifos.path.abspath()raisesOSError, the joined path is used unchanged for the case-normalization step.The second element of the returned tuple is the form used throughout the
sitemodule to compare paths on case-insensitive file systems, and is what populates theknown_pathssets that prevent duplicatesys.pathentries in various APIs within this module.
- class site.StartupState(known_paths=None)¶
Instances of this class accumulate interpreter startup configuration data from one or more site directories. They are the preferred interface for batching the processing of
.pthand.startfiles across multiple site directories, so that everysys.pathextension is visible before any startup code runs.The optional known_paths argument is a set of case-normalized paths (which can be produced by
makepath()) used to prevent duplicatesys.pathentries. WhenNone(the default), the set is built from the currentsys.path.main()implicitly uses an instance of this class.Typical use:
state = site.StartupState() for sitedir in site_dirs: state.addsitedir(sitedir) state.process()
اضافه شده در نسخهی 3.15.
- addsitedir(sitedir)¶
Read the
.pthand.startfiles in sitedir and record theirsys.pathextensions, deprecated.pthimportlines, and.startentry points on this state. The recorded data is not applied untilprocess()is called.
- addusersitepackages()¶
Add the per-user site-packages directory, if enabled and if it exists. The directory's startup data is accumulated for later processing by
process().
- addsitepackages(prefixes=None)¶
Add global site-packages directories, computed from prefixes or from the global
PREFIXESwhen prefixes isNone. Each directory's startup data is accumulated for later processing byprocess().
- process()¶
Apply the accumulated state by first adding the path extensions to
sys.path, then executing the.startfile entry points and.pthfileimportlines (deprecated).This method is not idempotent and must not be called more than once on the same instance. Doing so will apply the accumulated state more than once, re-running entry points and
importlines.
- site.addsitedir(sitedir, known_paths=None)¶
Add a directory to sys.path and parse the
.pthand.startfiles found in that directory. Typically used insitecustomizeorusercustomize(see above).The known_paths argument is an optional set of case-normalized paths used to prevent duplicate
sys.pathentries. WhenNone(the default), the set is built from the currentsys.path.For batched processing across multiple site directories, build a
StartupStateexplicitly and callStartupState.addsitedir()on it; that defers.pthand.startprocessing until a singleStartupState.process()call, ensuring everysys.pathextension is visible before any startup code runs.تغییر یافته در نسخهی 3.15: Also processes
.startfiles. See Startup entry points (.start files).
- site.getsitepackages(prefixes=None)¶
فهرستی شامل تمام پوشههای site-packages سراسری را برمیگرداند.
For each directory given in prefixes (or
PREFIXESif prefixes isNone), this function will compute its site-packages subdirectory depending on the system environment, and will return a list of full paths, which are not checked for existence.اضافه شده در نسخهی 3.2.
تغییر یافته در نسخهی 3.3: Added the optional prefixes parameter.
- site.getuserbase()¶
مسیر پوشهی پایهی کاربر،
USER_BASEرا برمیگرداند. اگر هنوز مقداردهی اولیه نشده باشد، این تابع آن را نیز با رعایتPYTHONUSERBASEتنظیم میکند.اضافه شده در نسخهی 3.2.
- site.getusersitepackages()¶
مسیر پوشهی site-packages اختصاصی کاربر،
USER_SITEرا برمیگرداند. اگر هنوز مقداردهی اولیه نشده باشد، این تابع آن را نیز با رعایتUSER_BASEتنظیم میکند. برای تشخیص اینکه آیا site-packages اختصاصی کاربر بهsys.pathاضافه شده است یا خیر، باید ازENABLE_USER_SITEاستفاده شود.اضافه شده در نسخهی 3.2.
رابط خط فرمان¶
ماژول site همچنین راهی برای دریافت پوشههای کاربر از خط فرمان فراهم میکند:
$ python -m site --user-site
/home/user/.local/lib/python3.11/site-packages
اگر بدون آرگومان فراخوانی شود، محتوای sys.path را در خروجی استاندارد چاپ میکند، پس از آن مقدار USER_BASE و اینکه آیا آن پوشه وجود دارد یا خیر، سپس همین مورد برای USER_SITE، و در نهایت مقدار ENABLE_USER_SITE را چاپ میکند.
- --user-base¶
مسیر پوشهی پایهی کاربر را چاپ میکند.
- --user-site¶
مسیر پوشهی site-packages کاربر را چاپ میکند.
اگر هر دو گزینه داده شده باشد، پایه کاربر (user base) و سایت کاربر (user site)، همیشه با همین ترتیب، چاپ میشوند و با os.pathsep جدا میشوند.
اگر گزینهای داده شود، اسکریپت با یکی از این مقدارها خارج میشود: 0 اگر پوشه site-packages کاربر فعال باشد، 1 اگر توسط کاربر غیرفعال شده باشد، 2 اگر به دلایل امنیتی یا توسط مدیر غیرفعال شده باشد، و مقداری بزرگتر از ۲ اگر خطایی وجود داشته باشد.
همچنین ملاحظه نمائید
PEP 370 -- پوشه site-packages برای هر کاربر
PEP 829 -- Startup entry points and the deprecation of import lines in
.pthfilesمقداردهی اولیهی مسیر جستجوی ماژول sys.path -- مقداردهی اولیهی
sys.path.