是否可以将subprocess.Popen()的返回值保存或存储到全局变量中?例如,
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
像这样的东西。我本质上是尝试从先前在代码中启动的子进程中读取输出,但我需要稍后开始读取。
答案 0 :(得分:2)
所以这最终成了一个愚蠢的疏忽。我需要做的就是调用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
答案 1 :(得分:1)
您需要在some_function
添加一行。我也提供了更好的解决方案。
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
更好的是:
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