How to call a variable inside main function from another program in python?
<p>I have two python files first.py and second.py</p>

<p>first.py looks like</p>

<pre><code>def main():
  #some computation
  first_variable=computation_result
</code></pre>

<p>second.py looks like</p>

<pre><code>import first
def main():
  b=getattr(first, first_variable)
  #computation
</code></pre>

<p>but I am getting No Attribute error. Is there any way to access a variable inside main() method in first.py through second.py?</p>

<p>You will want to read <a href="https://docs.python.org/3/tutorial/classes.html#a-word-about-names-and-objects" rel="nofollow">9.1 and 9.2</a> in the Tutorial and <a href="https://docs.python.org/3/reference/executionmodel.html#naming-and-binding" rel="nofollow">Naming and Binding</a> in the Language Reference.</p>

<p>In your example <code>first_variable</code> only <em>exists</em> within <code>first.main()</code>'s local scope - while it is executing. It isn't accessible to anything outside of that scope.</p>

<hr>

<p>You need to get  <code>first_variable</code> into <code>first</code>'s global scope - then in <code>second</code> you can use it with <code>first.first_variable</code>.</p>

<p>One way would be to return something from <code>first.main()</code> and assign it to <code>first_variable</code>.</p>

<pre><code>def main():
    return 2

first_variable = main()
</code></pre>

<p>Then in <code>second</code> you can use it:</p>

<pre><code>import first
times_3 = first.first_variable * 3
</code></pre>

python