[英]Saving return value of subprocess.Popen to a global variable
Is it possible to save or store the return value of a subprocess.Popen() to a global variable? 是否可以将subprocess.Popen()的返回值保存或存储到全局变量? 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.
我实质上是想从代码中较早启动的子流程中读取输出,但我需要稍后再开始读取。
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和global变量名称,以正确设置其值,如下所示:
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
You need to add one line to some_function
. 您需要向
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.