Team Ai
Apppublic

parthtamu/rag-code-assistant

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
runpy.html509 linesDownload Raw Back to docs
1<!DOCTYPE html>2 3<html lang="en" data-content_root="../">4  <head>5    <meta charset="utf-8" />6    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />7<meta property="og:title" content="runpy — Locating and executing Python modules" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/runpy.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/runpy.py The runpy module is used to locate and run Python modules without importing them first. Its main use is to implement the-m command line switch that allows scripts to be lo..." />12<meta property="og:image:width" content="1146" />13<meta property="og:image:height" content="600" />14<meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_runpy_bcbc0f22.png" />15<meta property="og:image:alt" content="Source code: Lib/runpy.py The runpy module is used to locate and run Python modules without importing them first. Its main use is to implement the-m command line switch that allows scripts to be lo..." />16<meta name="description" content="Source code: Lib/runpy.py The runpy module is used to locate and run Python modules without importing them first. Its main use is to implement the-m command line switch that allows scripts to be lo..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20    <title>runpy — Locating and executing Python modules &#8212; Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">21    22    <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />23    <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />24    <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" />25    <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" />26    <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />27    28    <script src="../_static/documentation_options.js?v=6b7c9ff5"></script>29    <script src="../_static/doctools.js?v=9bcbadda"></script>30    <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>31    <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script>32    33    <script src="../_static/sidebar.js"></script>34    35    <link rel="search" type="application/opensearchdescription+xml"36          title="Search within Python 3.15.0a6 documentation"37          href="../_static/opensearch.xml"/>38    <link rel="author" title="About these documents" href="../about.html" />39    <link rel="index" title="Index" href="../genindex.html" />40    <link rel="search" title="Search" href="../search.html" />41    <link rel="copyright" title="Copyright" href="../copyright.html" />42    <link rel="next" title="importlib — The implementation of import" href="importlib.html" />43    <link rel="prev" title="modulefinder — Find modules used by a script" href="modulefinder.html" />44    45      46      <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script>47      48      <link rel="canonical" href="https://docs.python.org/3/library/runpy.html">49      50    51 52    53    <style>54      @media only screen {55        table.full-width-table {56            width: 100%;57        }58      }59    </style>60<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">61    <link rel="shortcut icon" type="image/png" href="../_static/py.svg">62            <script type="text/javascript" src="../_static/copybutton.js"></script>63            <script type="text/javascript" src="../_static/menu.js"></script>64            <script type="text/javascript" src="../_static/search-focus.js"></script>65            <script type="text/javascript" src="../_static/themetoggle.js"></script> 66            <script type="text/javascript" src="../_static/rtd_switcher.js"></script>67            <meta name="readthedocs-addons-api-version" content="1">68 69  </head>70<body>71<div class="mobile-nav">72    <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"73           aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu">74    <nav class="nav-content" role="navigation">75        <label for="menuToggler" class="toggler__label">76            <span></span>77        </label>78        <span class="nav-items-wrapper">79            <a href="https://www.python.org/" class="nav-logo">80                <img src="../_static/py.svg" alt="Python logo">81            </a>82            <span class="version_switcher_placeholder"></span>83            <form role="search" class="search" action="../search.html" method="get">84                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">85                    <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>86                </svg>87                <input placeholder="Quick search" aria-label="Quick search" type="search" name="q">88                <input type="submit" value="Go">89            </form>90        </span>91    </nav>92    <div class="menu-wrapper">93        <nav class="menu" role="navigation" aria-label="main navigation">94            <div class="language_switcher_placeholder"></div>95            96<label class="theme-selector-label">97    Theme98    <select class="theme-selector" oninput="activateTheme(this.value)">99        <option value="auto" selected>Auto</option>100        <option value="light">Light</option>101        <option value="dark">Dark</option>102    </select>103</label>104  <div>105    <h4>Previous topic</h4>106    <p class="topless"><a href="modulefinder.html"107                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">modulefinder</span></code> — Find modules used by a script</a></p>108  </div>109  <div>110    <h4>Next topic</h4>111    <p class="topless"><a href="importlib.html"112                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">importlib</span></code> — The implementation of <code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a></p>113  </div>114  <script>115    document.addEventListener('DOMContentLoaded', () => {116        const title = document.querySelector('meta[property="og:title"]').content;117        const elements = document.querySelectorAll('.improvepage');118        const pageurl = window.location.href.split('?')[0];119        elements.forEach(element => {120            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));121            url.searchParams.set('pagetitle', title);122            url.searchParams.set('pageurl', pageurl);123            url.searchParams.set('pagesource', "library/runpy.rst");124            element.href = url.toString();125        });126    });127  </script>128  <div role="note" aria-label="source link">129    <h3>This page</h3>130    <ul class="this-page-menu">131      <li><a href="../bugs.html">Report a bug</a></li>132      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>133      <li>134        <a href="https://github.com/python/cpython/blob/main/Doc/library/runpy.rst?plain=1"135            rel="nofollow">Show source136        </a>137      </li>138      139    </ul>140  </div>141        </nav>142    </div>143</div>144 145  146    <div class="related" role="navigation" aria-label="Related">147      <h3>Navigation</h3>148      <ul>149        <li class="right" style="margin-right: 10px">150          <a href="../genindex.html" title="General Index"151             accesskey="I">index</a></li>152        <li class="right" >153          <a href="../py-modindex.html" title="Python Module Index"154             >modules</a> |</li>155        <li class="right" >156          <a href="importlib.html" title="importlib — The implementation of import"157             accesskey="N">next</a> |</li>158        <li class="right" >159          <a href="modulefinder.html" title="modulefinder — Find modules used by a script"160             accesskey="P">previous</a> |</li>161 162          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>163          <li><a href="https://www.python.org/">Python</a> &#187;</li>164          <li class="switchers">165            <div class="language_switcher_placeholder"></div>166            <div class="version_switcher_placeholder"></div>167          </li>168          <li>169              170          </li>171    <li id="cpython-language-and-version">172      <a href="../index.html">3.15.0a6 Documentation</a> &#187;173    </li>174 175          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>176          <li class="nav-item nav-item-2"><a href="modules.html" accesskey="U">Importing Modules</a> &#187;</li>177        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code> — Locating and executing Python modules</a></li>178                <li class="right">179                    180 181    <div class="inline-search" role="search">182        <form class="inline-search" action="../search.html" method="get">183          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">184          <input type="submit" value="Go">185        </form>186    </div>187                     |188                </li>189            <li class="right">190<label class="theme-selector-label">191    Theme192    <select class="theme-selector" oninput="activateTheme(this.value)">193        <option value="auto" selected>Auto</option>194        <option value="light">Light</option>195        <option value="dark">Dark</option>196    </select>197</label> |</li>198            199      </ul>200    </div>    201 202    <div class="document">203      <div class="documentwrapper">204        <div class="bodywrapper">205          <div class="body" role="main">206            207  <section id="module-runpy">208<span id="runpy-locating-and-executing-python-modules"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code> — Locating and executing Python modules<a class="headerlink" href="#module-runpy" title="Link to this heading">¶</a></h1>209<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/runpy.py">Lib/runpy.py</a></p>210<hr class="docutils" />211<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code> module is used to locate and run Python modules without212importing them first. Its main use is to implement the <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> command213line switch that allows scripts to be located using the Python module214namespace rather than the filesystem.</p>215<p>Note that this is <em>not</em> a sandbox module - all code is executed in the216current process, and any side effects (such as cached imports of other217modules) will remain in place after the functions have returned.</p>218<p>Furthermore, any functions and classes defined by the executed code are not219guaranteed to work correctly after a <code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code> function has returned.220If that limitation is not acceptable for a given use case, <a class="reference internal" href="importlib.html#module-importlib" title="importlib: The implementation of the import machinery."><code class="xref py py-mod docutils literal notranslate"><span class="pre">importlib</span></code></a>221is likely to be a more suitable choice than this module.</p>222<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code> module provides two functions:</p>223<dl class="py function">224<dt class="sig sig-object py" id="runpy.run_module">225<span class="sig-prename descclassname"><span class="pre">runpy.</span></span><span class="sig-name descname"><span class="pre">run_module</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">mod_name</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">init_globals</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">run_name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">alter_sys</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#runpy.run_module" title="Link to this definition">¶</a></dt>226<dd><p id="index-0">Execute the code of the specified module and return the resulting module’s227globals dictionary. The module’s code is first located using the standard228import mechanism (refer to <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a> for details) and then executed in a229fresh module namespace.</p>230<p>The <em>mod_name</em> argument should be an absolute module name.231If the module name refers to a package rather than a normal232module, then that package is imported and the <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> submodule within233that package is then executed and the resulting module globals dictionary234returned.</p>235<p>The optional dictionary argument <em>init_globals</em> may be used to pre-populate236the module’s globals dictionary before the code is executed.237<em>init_globals</em> will not be modified. If any of the special global variables238below are defined in <em>init_globals</em>, those definitions are239overridden by <code class="xref py py-func docutils literal notranslate"><span class="pre">run_module()</span></code>.</p>240<p>The special global variables <code class="docutils literal notranslate"><span class="pre">__name__</span></code>, <code class="docutils literal notranslate"><span class="pre">__spec__</span></code>, <code class="docutils literal notranslate"><span class="pre">__file__</span></code>,241<code class="docutils literal notranslate"><span class="pre">__loader__</span></code> and <code class="docutils literal notranslate"><span class="pre">__package__</span></code> are set in the globals dictionary before242the module code is executed. (Note that this is a minimal set of variables -243other variables may be set implicitly as an interpreter implementation244detail.)</p>245<p><code class="docutils literal notranslate"><span class="pre">__name__</span></code> is set to <em>run_name</em> if this optional argument is not246<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, to <code class="docutils literal notranslate"><span class="pre">mod_name</span> <span class="pre">+</span> <span class="pre">'.__main__'</span></code> if the named module is a247package and to the <em>mod_name</em> argument otherwise.</p>248<p><code class="docutils literal notranslate"><span class="pre">__spec__</span></code> will be set appropriately for the <em>actually</em> imported249module (that is, <code class="docutils literal notranslate"><span class="pre">__spec__.name</span></code> will always be <em>mod_name</em> or250<code class="docutils literal notranslate"><span class="pre">mod_name</span> <span class="pre">+</span> <span class="pre">'.__main__'</span></code>, never <em>run_name</em>).</p>251<p><code class="docutils literal notranslate"><span class="pre">__file__</span></code>, <code class="docutils literal notranslate"><span class="pre">__loader__</span></code> and <code class="docutils literal notranslate"><span class="pre">__package__</span></code> are252<a class="reference internal" href="../reference/datamodel.html#import-mod-attrs"><span class="std std-ref">set as normal</span></a> based on the module spec.</p>253<p>If the argument <em>alter_sys</em> is supplied and evaluates to <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>,254then <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is updated with the value of <code class="docutils literal notranslate"><span class="pre">__file__</span></code> and255<code class="docutils literal notranslate"><span class="pre">sys.modules[__name__]</span></code> is updated with a temporary module object for the256module being executed. Both <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.modules[__name__]</span></code>257are restored to their original values before the function returns.</p>258<p>Note that this manipulation of <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> is not thread-safe. Other threads259may see the partially initialised module, as well as the altered list of260arguments. It is recommended that the <code class="docutils literal notranslate"><span class="pre">sys</span></code> module be left alone when261invoking this function from threaded code.</p>262<div class="admonition seealso">263<p class="admonition-title">See also</p>264<p>The <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> option offering equivalent functionality from the265command line.</p>266</div>267<div class="versionchanged">268<p><span class="versionmodified changed">Changed in version 3.1: </span>Added ability to execute packages by looking for a <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> submodule.</p>269</div>270<div class="versionchanged">271<p><span class="versionmodified changed">Changed in version 3.2: </span>Added <code class="docutils literal notranslate"><span class="pre">__cached__</span></code> global variable (see <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-3147/"><strong>PEP 3147</strong></a>).</p>272</div>273<div class="versionchanged">274<p><span class="versionmodified changed">Changed in version 3.4: </span>Updated to take advantage of the module spec feature added by275<span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-0451/"><strong>PEP 451</strong></a>. This allows <code class="docutils literal notranslate"><span class="pre">__cached__</span></code> to be set correctly for modules276run this way, as well as ensuring the real module name is always277accessible as <code class="docutils literal notranslate"><span class="pre">__spec__.name</span></code>.</p>278</div>279<div class="versionchanged">280<p><span class="versionmodified changed">Changed in version 3.12: </span>The setting of <code class="docutils literal notranslate"><span class="pre">__cached__</span></code>, <code class="docutils literal notranslate"><span class="pre">__loader__</span></code>, and281<code class="docutils literal notranslate"><span class="pre">__package__</span></code> are deprecated. See282<a class="reference internal" href="importlib.html#importlib.machinery.ModuleSpec" title="importlib.machinery.ModuleSpec"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModuleSpec</span></code></a> for alternatives.</p>283</div>284<div class="versionchanged">285<p><span class="versionmodified changed">Changed in version 3.15: </span><code class="docutils literal notranslate"><span class="pre">__cached__</span></code> is no longer set.</p>286</div>287</dd></dl>288 289<dl class="py function">290<dt class="sig sig-object py" id="runpy.run_path">291<span class="sig-prename descclassname"><span class="pre">runpy.</span></span><span class="sig-name descname"><span class="pre">run_path</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">path_name</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">init_globals</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">run_name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#runpy.run_path" title="Link to this definition">¶</a></dt>292<dd><p id="index-4">Execute the code at the named filesystem location and return the resulting293module’s globals dictionary. As with a script name supplied to the CPython294command line, <em>file_path</em> may refer to a Python source file, a295compiled bytecode file or a valid <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> entry containing a296<a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module297(e.g. a zipfile containing a top-level <code class="file docutils literal notranslate"><span class="pre">__main__.py</span></code> file).</p>298<p>For a simple script, the specified code is simply executed in a fresh299module namespace. For a valid <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> entry (typically a zipfile or300directory), the entry is first added to the beginning of <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>. The301function then looks for and executes a <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module using the302updated path. Note that there is no special protection against invoking303an existing <code class="docutils literal notranslate"><span class="pre">__main__</span></code> entry located elsewhere on <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> if304there is no such module at the specified location.</p>305<p>The optional dictionary argument <em>init_globals</em> may be used to pre-populate306the module’s globals dictionary before the code is executed.307<em>init_globals</em> will not be modified. If any of the special global variables308below are defined in <em>init_globals</em>, those definitions are309overridden by <code class="xref py py-func docutils literal notranslate"><span class="pre">run_path()</span></code>.</p>310<p>The special global variables <code class="docutils literal notranslate"><span class="pre">__name__</span></code>, <code class="docutils literal notranslate"><span class="pre">__spec__</span></code>, <code class="docutils literal notranslate"><span class="pre">__file__</span></code>,311<code class="docutils literal notranslate"><span class="pre">__loader__</span></code> and <code class="docutils literal notranslate"><span class="pre">__package__</span></code> are set in the globals dictionary before312the module code is executed. (Note that this is a minimal set of variables -313other variables may be set implicitly as an interpreter implementation314detail.)</p>315<p><code class="docutils literal notranslate"><span class="pre">__name__</span></code> is set to <em>run_name</em> if this optional argument is not316<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> and to <code class="docutils literal notranslate"><span class="pre">'&lt;run_path&gt;'</span></code> otherwise.</p>317<p>If <em>file_path</em> directly references a script file (whether as source318or as precompiled byte code), then <code class="docutils literal notranslate"><span class="pre">__file__</span></code> will be set to319<em>file_path</em>, and <code class="docutils literal notranslate"><span class="pre">__spec__</span></code>, <code class="docutils literal notranslate"><span class="pre">__loader__</span></code> and320<code class="docutils literal notranslate"><span class="pre">__package__</span></code> will all be set to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>321<p>If <em>file_path</em> is a reference to a valid <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> entry, then322<code class="docutils literal notranslate"><span class="pre">__spec__</span></code> will be set appropriately for the imported <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>323module (that is, <code class="docutils literal notranslate"><span class="pre">__spec__.name</span></code> will always be <code class="docutils literal notranslate"><span class="pre">__main__</span></code>).324<code class="docutils literal notranslate"><span class="pre">__file__</span></code>, <code class="docutils literal notranslate"><span class="pre">__loader__</span></code> and <code class="docutils literal notranslate"><span class="pre">__package__</span></code> will be325<a class="reference internal" href="../reference/datamodel.html#import-mod-attrs"><span class="std std-ref">set as normal</span></a> based on the module spec.</p>326<p>A number of alterations are also made to the <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module. Firstly,327<a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> may be altered as described above. <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is updated328with the value of <em>file_path</em> and <code class="docutils literal notranslate"><span class="pre">sys.modules[__name__]</span></code> is updated329with a temporary module object for the module being executed. All330modifications to items in <code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code> are reverted before the function331returns.</p>332<p>Note that, unlike <a class="reference internal" href="#runpy.run_module" title="runpy.run_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">run_module()</span></code></a>, the alterations made to <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>333are not optional in this function as these adjustments are essential to334allowing the execution of <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> entries. As the thread-safety335limitations still apply, use of this function in threaded code should be336either serialised with the import lock or delegated to a separate process.</p>337<div class="admonition seealso">338<p class="admonition-title">See also</p>339<p><a class="reference internal" href="../using/cmdline.html#using-on-interface-options"><span class="std std-ref">Interface options</span></a> for equivalent functionality on the340command line (<code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">path/to/script</span></code>).</p>341</div>342<div class="versionadded">343<p><span class="versionmodified added">Added in version 3.2.</span></p>344</div>345<div class="versionchanged">346<p><span class="versionmodified changed">Changed in version 3.4: </span>Updated to take advantage of the module spec feature added by347<span class="target" id="index-5"></span><a class="pep reference external" href="https://peps.python.org/pep-0451/"><strong>PEP 451</strong></a>. This allows <code class="docutils literal notranslate"><span class="pre">__cached__</span></code> to be set correctly in the348case where <code class="docutils literal notranslate"><span class="pre">__main__</span></code> is imported from a valid <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> entry rather349than being executed directly.</p>350</div>351<div class="versionchanged">352<p><span class="versionmodified changed">Changed in version 3.12: </span>The setting of <code class="docutils literal notranslate"><span class="pre">__cached__</span></code>, <code class="docutils literal notranslate"><span class="pre">__loader__</span></code>, and353<code class="docutils literal notranslate"><span class="pre">__package__</span></code> are deprecated.</p>354</div>355<div class="versionchanged">356<p><span class="versionmodified changed">Changed in version 3.15: </span><code class="docutils literal notranslate"><span class="pre">__cached__</span></code> is no longer set.</p>357</div>358</dd></dl>359 360<div class="admonition seealso">361<p class="admonition-title">See also</p>362<dl class="simple">363<dt><span class="target" id="index-6"></span><a class="pep reference external" href="https://peps.python.org/pep-0338/"><strong>PEP 338</strong></a> – Executing modules as scripts</dt><dd><p>PEP written and implemented by Nick Coghlan.</p>364</dd>365<dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://peps.python.org/pep-0366/"><strong>PEP 366</strong></a> – Main module explicit relative imports</dt><dd><p>PEP written and implemented by Nick Coghlan.</p>366</dd>367<dt><span class="target" id="index-8"></span><a class="pep reference external" href="https://peps.python.org/pep-0451/"><strong>PEP 451</strong></a> – A ModuleSpec Type for the Import System</dt><dd><p>PEP written and implemented by Eric Snow</p>368</dd>369</dl>370<p><a class="reference internal" href="../using/cmdline.html#using-on-general"><span class="std std-ref">Command line and environment</span></a> - CPython command line details</p>371<p>The <a class="reference internal" href="importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.import_module()</span></code></a> function</p>372</div>373</section>374 375 376            <div class="clearer"></div>377          </div>378        </div>379      </div>380      <div class="sphinxsidebar" role="navigation" aria-label="Main">381        <div class="sphinxsidebarwrapper">382  <div>383    <h4>Previous topic</h4>384    <p class="topless"><a href="modulefinder.html"385                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">modulefinder</span></code> — Find modules used by a script</a></p>386  </div>387  <div>388    <h4>Next topic</h4>389    <p class="topless"><a href="importlib.html"390                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">importlib</span></code> — The implementation of <code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a></p>391  </div>392  <script>393    document.addEventListener('DOMContentLoaded', () => {394        const title = document.querySelector('meta[property="og:title"]').content;395        const elements = document.querySelectorAll('.improvepage');396        const pageurl = window.location.href.split('?')[0];397        elements.forEach(element => {398            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));399            url.searchParams.set('pagetitle', title);400            url.searchParams.set('pageurl', pageurl);401            url.searchParams.set('pagesource', "library/runpy.rst");402            element.href = url.toString();403        });404    });405  </script>406  <div role="note" aria-label="source link">407    <h3>This page</h3>408    <ul class="this-page-menu">409      <li><a href="../bugs.html">Report a bug</a></li>410      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>411      <li>412        <a href="https://github.com/python/cpython/blob/main/Doc/library/runpy.rst?plain=1"413            rel="nofollow">Show source414        </a>415      </li>416      417    </ul>418  </div>419        </div>420<div id="sidebarbutton" title="Collapse sidebar">421<span>«</span>422</div>423 424      </div>425      <div class="clearer"></div>426    </div>  427    <div class="related" role="navigation" aria-label="Related">428      <h3>Navigation</h3>429      <ul>430        <li class="right" style="margin-right: 10px">431          <a href="../genindex.html" title="General Index"432             >index</a></li>433        <li class="right" >434          <a href="../py-modindex.html" title="Python Module Index"435             >modules</a> |</li>436        <li class="right" >437          <a href="importlib.html" title="importlib — The implementation of import"438             >next</a> |</li>439        <li class="right" >440          <a href="modulefinder.html" title="modulefinder — Find modules used by a script"441             >previous</a> |</li>442 443          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>444          <li><a href="https://www.python.org/">Python</a> &#187;</li>445          <li class="switchers">446            <div class="language_switcher_placeholder"></div>447            <div class="version_switcher_placeholder"></div>448          </li>449          <li>450              451          </li>452    <li id="cpython-language-and-version">453      <a href="../index.html">3.15.0a6 Documentation</a> &#187;454    </li>455 456          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>457          <li class="nav-item nav-item-2"><a href="modules.html" >Importing Modules</a> &#187;</li>458        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code> — Locating and executing Python modules</a></li>459                <li class="right">460                    461 462    <div class="inline-search" role="search">463        <form class="inline-search" action="../search.html" method="get">464          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">465          <input type="submit" value="Go">466        </form>467    </div>468                     |469                </li>470            <li class="right">471<label class="theme-selector-label">472    Theme473    <select class="theme-selector" oninput="activateTheme(this.value)">474        <option value="auto" selected>Auto</option>475        <option value="light">Light</option>476        <option value="dark">Dark</option>477    </select>478</label> |</li>479            480      </ul>481    </div>  482    <div class="footer">483    &copy; <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.484    <br>485    This page is licensed under the Python Software Foundation License Version 2.486    <br>487    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.488    <br>489    490      See <a href="/license.html">History and License</a> for more information.<br>491    492    493    <br>494 495    The Python Software Foundation is a non-profit corporation.496<a href="https://www.python.org/psf/donations/">Please donate.</a>497<br>498    <br>499      Last updated on Mar 10, 2026 (08:58 UTC).500    501      <a href="/bugs.html">Found a bug</a>?502    503    <br>504 505    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.506    </div>507 508  </body>509</html>