擅长:python、mysql、java
<p>如果希望代码仅在直接执行时触发,请使用<code>if __name__ == '__main__'</code>条件:</p>
<blockquote>
<p><code>__name__</code> is the name of the scope in which top-level code executes.
A module’s <code>__name__</code> is set equal to <code>'__main__'</code> when read from standard
input, a script, or from an interactive prompt.</p>
<p>A module can discover whether or not it is running in the main scope
by checking its own <strong>name</strong>, which allows a common idiom for
conditionally executing code in a module when it is run as a script or
with python -m but not when it is imported.</p>
</blockquote>
<pre><code>if __name__ == "__main__":
# execute only if run as a script
main()
</code></pre>