interacting with objects in execfile/subprocess.call on python file with arguments
<p>Python novice here.</p>

<p>I am trying to interact with the variables/objects in a python file that requires arguments for its data. <strong>Let's say I can only get this data from arguments</strong>, rather than make a script that includes arguments that would be passed (which means I must use execfile or subprocess.call).</p>

<p>Let's say this was my python file, foo.py:</p>

<pre><code>bar = 123
print("ran foo.py, bar = %d" % bar)
</code></pre>

<p>Of course, there would be more to the file to parse arguments, but that is irrelevant.</p>

<p>Now, in a python shell (either python or ipython in a terminal):</p>

<pre><code>&gt;&gt;&gt; import subprocess
&gt;&gt;&gt; subprocess.call("python foo.py 'args'", shell=True)
ran foo.py, bar = 123
0
&gt;&gt;&gt; bar
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
NameError: name 'bar' is not defined
</code></pre>

<p>As the example output above shows, bar is not defined after stdout from foo.py.</p>

<p>Is there any way to interact with variables or data objects in a python file called by execfile or subprocess.call? Normally I would eval in a REPL or run in an IDE so I can test out values and objects after execution, but I cannot figure out how to do this with a python file that builds data from parsed arguments.</p>

<p>Does anyone know how I can do this? Thanks for your consideration, at any rate.</p>

<p>Is foo.py under your control? If yes, simply change it, such that it can be run by being imported as module and interacted with.
If no, you may need to catch the output as string and newly build your variable <code>bar</code> from it.
How you capture the output of a subprocess is answered here for example: 
<a href="http://stackoverflow.com/questions/4760215/running-shell-command-from-python-and-capturing-the-output">Running shell command from Python and capturing the output</a></p>

python ipython