1

I am trying to access a variable from a python module which is being run as a script. The variable is defined in the if __name__ == "__main__":

The code I am working with looks something like this:

MyCode.py
cmd = 'python OtherCode.py'
os.system(cmd) # Run the other module as a python script

OtherCode.py
if __name__ == "__main__":
    var = 'This is the variable I want to access'

I was wondering if there was a way to access this variable while still running the OtherCode.py as a script.

Random Davis
  • 6,662
  • 4
  • 14
  • 24
Laskii
  • 21
  • 3
  • 3
    The variable is gone as soon as `os.system(cmd)` returns, as it was only ever define in that process. If you just want the *value* that was assigned to the variable, you'll need to investigate various methods of interprocess communication, ad `OtherCode.py` will have to be modified to cooperate. – chepner Dec 02 '20 at 22:06
  • 3
    Why not just import the other script? Why does it have to be run via `cmd`? Why do none of these options here work for you? https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-script-from-another-script – Random Davis Dec 02 '20 at 22:07
  • @RandomDavis: Well, if the variable definition is protected by an import guard as shown, that won't work. – ShadowRanger Dec 02 '20 at 22:17

3 Answers3

2

You can use the runpy module to import the module as __main__ then extract the variable from the returned dictionary:

import runpy
vars = runpy.run_module("OtherCode", run_name="__main__")
desired_var = vars["var"] # where "var" is the variable name you want
Aplet123
  • 33,825
  • 1
  • 29
  • 55
1

When you use os.system, it runs the specified command as a completely separate process. You would need to pass the variable through some sort of OS-level communication mechanism: stdout, a socket, shared memory, etc.

But since both scripts are Python, it would be much easier to just import OtherCode. (Though note that you will need to set up OtherCode.py inside of a package so that Python knows it can be imported.)

0x5453
  • 12,753
  • 1
  • 32
  • 61
0

While this fix might not be ideal (or what people are looking for if they google it) I ended up printing out the variable and then used subprocess to get the stdout as a variable:

MyCode.py
cmd = 'python OtherCode.py'   
cmdOutput =  subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout

OtherCode.py
if __name__ == "__main__":
    var = 'This is the variable I want to access'
    print(var)

In this case the cmdOutput == var

Laskii
  • 21
  • 3