0

Is it possible to save or store the return value of a subprocess.Popen() to a global variable? For example,

global_var = none
 ...
 def some_function():
    p = subprocess.Popen(...,stdout=subprocess.PIPE, shell=True)
    global_var = p

 def some_function_2():
    x = global_var.stdout

Something like this. I'm essentially trying to read output from a subprocess that is started earlier in code but I need to begin the read later on.

Chris
  • 179
  • 12
  • what happens when you do this? what do you expect to happen? Comparing actual behavior to expected behavior is crucial in determining how others can help. – JacobIRR Jun 19 '18 at 01:05
  • There is nothing special about global variables. Any variable declared at the outermost level of indentation is global. If you simply write `p = subprocess.Popen(...)`, outside of any function or class definition, p will be a global variable. So the Popen object, like any other, can be stored anywhere. – Paul Cornelius Jun 19 '18 at 01:06
  • @JacobIRR, so performing x = global_var.stdout does not work since the value of global_var.stdout is None for whatever reason and not the file object returned from subprocess.Popen. – Chris Jun 19 '18 at 01:12

2 Answers2

2

So this ended up being a silly oversight. All I needed to do was call global and the global variable name inside the function to set its value correctly like so:

global_var = none
 ...
 def some_function():
    p = subprocess.Popen(...,stdout=subprocess.PIPE, shell=True)
    global global_var
    global_var = p

 def some_function_2():
    x = global_var.stdout
Chris
  • 179
  • 12
1

You need to add one line to some_function. I also give a better solution.

 global_var = None  
 ...
 def some_function():
    global global_var # without this line, Python will create a local named global_variable
    p = subprocess.Popen(...,stdout=subprocess.PIPE, shell=True)
    global_var = p

 def some_function_2():
    x = global_var.stdout

Better is:

 def some_function():
    # I assume this function does some other things, otherwise
    # you don't need to write a function to just call another.
    p = subprocess.Popen(...,stdout=subprocess.PIPE, shell=
    return p

 my_process = some_function()

 def some_function_2():
    x = my_process.stdout
Paul Cornelius
  • 9,245
  • 1
  • 15
  • 24