变量不会在Python脚本之间传递

2024-03-29 03:12:58 发布

您现在位置:Python中文网/ 问答频道 /正文

由于某些原因,我无法将变量从一个Python文件传递到另一个Python文件。请参阅下面的文件。你知道吗

pullgps.py

from lenny1 import * 
import time

while (1):

  print lenny1.lat
  print lenny1.lon
  print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
  time.sleep(6)

lenny1.py

import gps

# Listen on port 2947 (gpsd) of localhost
session = gps.gps("localhost", "2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)

while True:
    try:
        report = session.next()
        # Wait for a 'TPV' report and display the current time
        # To see all report data, uncomment the line below
        # print report
        if report['class'] == 'TPV':
             if hasattr(report, 'lat'):
                  lat = report.lat ### export to pullgps
             if hasattr(report, 'lon'):
                  lon = report.lon ### export to pullgps
    except KeyError:
        pass
    except KeyboardInterrupt:
        quit()
    except StopIteration:
        session = None
        print "GPSD has terminated"

当我打印report.lonreport.lon时,lenny.py可以独立工作。只是无法将变量导出到pullgps.py。它应该很简单,但是由于某些原因,变量不会传递。谢谢!你知道吗


Tags: 文件pyimportreportiftimesession原因
1条回答
网友
1楼 · 发布于 2024-03-29 03:12:58

您正在使用from lenny1 import *,它将lenny1.py中的所有内容导入全局命名空间。不仅如此,在第一次导入时,您实际上正在运行lenny1.py中的所有内容,其中包含一个while循环,该循环可能会阻塞。这是非常糟糕的代码实践。但是,我认为您遇到的问题是,在使用带星号的导入时引用了lenny1.lonlenny1.lat。只要打印lonlat,如果循环终止,原则上它应该“工作”。你知道吗

相关问题 更多 >