【问题标题】:Acessing for loop varible in another python script在另一个python脚本中访问for循环变量
【发布时间】:2022-11-26 02:07:45
【问题描述】:

我的文件名为file1.py,代码如下。 `

import os

global x
def a_function():
    while True:
        for x in range(12):

            cmd=f'rosbag record -O /home/mubashir/catkin_ws/src/germany1_trush/rosbag/{x}.bag /web_cam --duration 5 '
            os.system(cmd)
        
a_function()


I want to acess x in another python scriptfile2.py`代码如下

from file1 import x
print(x)

但问题是当我运行 file2.py 时执行了 file1.py。我只想在 file2.py 中打印 x

无法在另一个 python 脚本中访问全局变量。

【问题讨论】:

    标签: python loops module scope global


    【解决方案1】:

    为了纠正这个问题,添加一个 if 语句来检查 file1.py 本身是否正在运行。如果是,则 __name__ 应等于 '__main__'

    您希望file2.py 读取的代码应该在 if 语句之外,并且仅当 file1.py 运行时您想要执行的所有代码都应该在 if 语句内。例如:

    import os
    
    global x
    
    if __name__ == '__main__':
        def a_function():
            while True:
                for x in range(12):
    
                    cmd=f'rosbag record -O /home/mubashir/catkin_ws/src/germany1_trush/rosbag/{x}.bag /web_cam --duration 5 '
                    os.system(cmd)
    
        a_function()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      相关资源
      最近更新 更多