我是python的新手,并且在让我的代码工作时遇到了问题。
我有两个不同的模块,在模块a.py中我将所有方法放在模块b.py中我把逻辑。
我正在使用的开发环境是Sypder。
# module a
import serial
ser = serial.Serial()
def serWrite ( str ):
ser.write (str + "\x0D")
print "Write data :", str + "\x0D"
time.sleep(0.1)
return
def configuration():
flagAT = 0
while (flagAT == 0):
serWrite("at")
while True:
ok = ser.readline()
if (ok[0:2] == "OK"):
print ("AT OK, DEVICE CONNECTED" + "\x0D")
flagAT = 1
break
else:
print "DEVICE NOT CONNECTED OR NOT WORKING"
break
print("Starting with configuration")
模块b.py:
#module b
import serial
import a
ser = serial.Serial()
ser.port = "/dev/ttyS1"
ser.baudrate = 115200
### more serial configuration here###
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
configuration()
现在问题: 当我在运行a.py INSIDE Spyder后运行模块b.py时,一切正常。
但是:Spyder代码分析告诉我
'a' imported but unused
当我尝试调用模块b.py OUTSIDE Spyder时出现以下错误
pi@(none) ~/WorkingDirectory $ python b.py
Traceback (most recent call last):
File "b.py", line 83, in <module>
configuration()
NameError: name 'configuration' is not defined
使用以下命令导入配置()
import a
a.configuration()
给出以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "/home/workingDirectory/test.py", line 85, in <module>
a.configuration()
File "a.py", line 336, in configuration
serWrite("at")
File "a.py", line 16, in serWrite
ser.write (str + "\x0D")
File "build/bdist.linux-i686/egg/serial/serialposix.py", line 490, in write
serial.serialutil.SerialException: Attempting to use a port that is not open
我不明白为什么我的程序在spyder中运行没有问题但不在外面。 有人可以帮忙吗?
答案 0 :(得分:2)
您需要将模块b更改为:
#module b
import serial
from a import ser, configuration
#ser = serial.Serial()
ser.port = "/dev/ttyS1"
ser.baudrate = 115200
### more serial configuration here###
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
configuration()