0

Python novice here.

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

Let's say this was my python file, foo.py:

bar = 123
print("ran foo.py, bar = %d" % bar)

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

Now, in a python shell (either python or ipython in a terminal):

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

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

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.

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

Alnitak
  • 2,068
  • 2
  • 12
  • 24

1 Answers1

0

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 bar from it. How you capture the output of a subprocess is answered here for example: Running shell command from Python and capturing the output

Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712