如何从另一个python文件中获取函数参数

发布于 2025-02-11 08:13:38 字数 889 浏览 0 评论 0原文

我在Python中有三个文件,称为A.Py,B.Py和C.Py 我想使用以下代码段做点什么,以确定

if __name__ == "__main__":
    subprocess.Popen('python A.py', shell=True).wait()
    subprocess.Popen('python C.py', shell=True)

程序运行时的执行顺序(我从b.py内运行程序),它等待A.Py的响应以接收Reciv_func中的值(a,a,,, a, b,c)函数,可能需要一些时间才能使A.Py接收结果,所以我等到第一次运行A.Py

我的问题是在B.Py文件中我可以访问值reciv_func(a,, b,c)在功能中,但我在外面无法访问它们,我甚至在全球范围内定义了

async def main():
     
     url = f'my_url'
     async with websockets.connect(url) as client:
         while True:
             data = json.loads(await client.recv())['data']
             B.reciv_func(data['x']['y']['z'])


 if __name__ == "__main__":
     asyncio.run(main())

变量

reciv_func(a,b,c):
    global a1
    global b2
    global c3
    a1 = a
    b2 = b
    c3 = c
    
# out of reciv_func no access to a1 , b2 , c3

I have three files in Python called A.py, B.py and C.py
I wanted to do something with the following code snippet to determine the execution order (I run the program from within B.py)

if __name__ == "__main__":
    subprocess.Popen('python A.py', shell=True).wait()
    subprocess.Popen('python C.py', shell=True)

When the program runs, it waits for a response from A.py to receive the values in the reciv_func (a, b, c) function, it may take some time for A.py to receive the results, so I wait until the first Run A.py

My problem is that in the B.py file I have access to the values reciv_func (a, b, c) in the function but I have no access to them outside I have even defined the variables globally

A.py

async def main():
     
     url = f'my_url'
     async with websockets.connect(url) as client:
         while True:
             data = json.loads(await client.recv())['data']
             B.reciv_func(data['x']['y']['z'])


 if __name__ == "__main__":
     asyncio.run(main())

B.py

reciv_func(a,b,c):
    global a1
    global b2
    global c3
    a1 = a
    b2 = b
    c3 = c
    
# out of reciv_func no access to a1 , b2 , c3

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

飘逸的'云 2025-02-18 08:13:38

如果要访问 a1,b2,c3 a.py 中访问函数后:

b.reciv_func(data ['x''] ['y y y '] ['z'])

最简单的方法是使用返回,而无需任何全局变量。例如,如果您编辑 b.py as:

reciv_func(a,b,c):
    return a,b,c

可以在调用函数时返回所需的变量:

a1,b2,c3 = B.reciv_func(data['x']['y']['z'])

这样,您可以访问对应于 a1,b2,c3 <的值/em>按照您的意愿 a.py

If you want to access a1,b2,c3 in your A.py after calling the function:

B.reciv_func(data['x']['y']['z'])

The easiest way is to use return, without the need for any global variables. For example, if you edit B.py as:

reciv_func(a,b,c):
    return a,b,c

You can return the desired variables when you call the function:

a1,b2,c3 = B.reciv_func(data['x']['y']['z'])

In this way, you can access the values corresponding to a1,b2,c3 as you wish within A.py.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文