变量元';不能在Python脚本之间传递
由于某些原因,我无法将变量从一个Python文件传递到另一个Python文件。请参阅下面的文件变量元';不能在Python脚本之间传递,python,Python,由于某些原因,我无法将变量从一个Python文件传递到另一个Python文件。请参阅下面的文件 pullgps.py: from lenny1 import * import time while (1): print lenny1.lat print lenny1.lon print ">>>>>>>>>>>>>>>>>>>>>>>>
pullgps.py
:
from lenny1 import *
import time
while (1):
print lenny1.lat
print lenny1.lon
print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
time.sleep(6)
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"
lenny1.py
:
from lenny1 import *
import time
while (1):
print lenny1.lat
print lenny1.lon
print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
time.sleep(6)
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.lon
和report.lon
时,lenny.py
可以独立工作。只是无法将变量导出到pullgps.py
。它应该很简单,但由于某些原因,变量不会传递。谢谢 您使用的是from lenny1 import*
,它将lenny1.py中的所有内容导入全局名称空间。不仅如此,在第一次导入时,您实际上正在运行lenny1.py中的所有内容,其中包含一个可能会阻塞的while循环。这是非常糟糕的代码实践。但是,我认为您遇到的问题是,在使用带星号的导入时,您正在引用lenny1.lon
和lenny1.lat
。只要打印lon
和lat
,如果循环终止,原则上它应该“起作用”。我认为您应该阅读有关导入声明的内容。谢谢,如您所述。它只是挂着。更改为导入lenny1并删除while循环。它仍然挂起。您删除了哪个while循环?lenny1.py中的一个看起来将永远阻塞。另外,您是否计划同时运行这两个进程?正如用户3591723(注释现已删除)所指出的那样,因为这不是实现的方法。删除了pullgps.py中的循环。对,那么您不应该期望代码正常工作。您可能需要研究线程或多处理,以获得满足您需要的功能。但它看起来和你现在拥有的完全不同。