2017-05-05 74 views
0

由于某些原因,我无法将变量从一个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" 

lenny.py当我打印report.lonreport.lon工作在自己的罚款。只是无法将变量导出到pullgps.py。它应该很简单,但由于某些原因,变量不会通过。谢谢!

+2

我想你应该阅读[this](https://docs.python.org/3/tutorial/modules.html)关于import语句。 – user3591723

回答

0

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

+0

谢谢,你提到过。它只是挂起。更改为导入lenny1并删除了while循环。它仍然挂起。 – hahobson

+0

哪个while循环删除了? lenny1.py中的一个看起来会永久阻塞。 – Evey

+0

另外,你打算同时运行这两个进程吗?因为这不是这样做的,正如user3591723指出的那样(现在评论已删除)。 – Evey