Python 不是 运行 作为 pyserial class 的主要内容
Python not running as main for a pyserial class
我做了一个小 class 来打开 python 上的串行端口 (ttyUSB0),但是当我尝试 运行 它作为 main 它给了我很多我真的不知道的东西。
我希望 class 在我 运行 时创建一个串口实例,并让适当的函数(或方法)返回我对 [=32= 的要求] ]e的例子。相反,当我 运行:
时,我得到以下输出
$ python3 entrada.py
我怎样才能运行如愿以偿?
这是 entrada.py
的代码
import serial #for port opening
import sys #for exceptions
from collections import __main__
#
#configure the serial connections (the parameters differs on the device you are connecting to)
class Serializer:
def __init__(self, port, baudrate=9600, timeout=5):
self.port = serial.Serial(port = port, baudrate=baudrate,
timeout=timeout, writeTimeout=timeout)
def open(self):
''' Open the serial port.'''
self.port.open()
def close(self):
''' Close the serial port.'''
self.port.close()
def send(self, msg):
self.prot.write(msg)
def recv(self):
return self.port.readline()
PORT = '/dev/ttyUSB0' #Esto puede necesitar cambiarse
def main():
test_port = Serializer(port = PORT)
try:
test_port().open()
except:
print ("Could not open serial port: ", sys.exc_info()[0])
sys.exit(2)
while True:
print(test_port.recv())
if __name__ == __main__:
main()
这是输出:
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict
class Point(tuple):
'Point(x, y)'
__slots__ = ()
_fields = ('x', 'y')
def __new__(_cls, x, y):
'Create new instance of Point(x, y)'
return _tuple.__new__(_cls, (x, y))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new Point object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 2:
raise TypeError('Expected 2 arguments, got %d' % len(result))
return result
def _replace(_self, **kwds):
'Return a new Point object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('x', 'y'), _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % list(kwds))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + '(x=%r, y=%r)' % self
@property
def __dict__(self):
'A new OrderedDict mapping field names to their values'
return OrderedDict(zip(self._fields, self))
def _asdict(self):
'Return a new OrderedDict which maps field names to their values.'
return self.__dict__
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
def __getstate__(self):
'Exclude the OrderedDict from pickling'
return None
x = _property(_itemgetter(0), doc='Alias for field number 0')
y = _property(_itemgetter(1), doc='Alias for field number 1')
Point: x= 3.000 y= 4.000 hypot= 5.000
Point: x=14.000 y= 0.714 hypot=14.018
Point(x=100, y=22)
Point3D(x, y, z)
TestResults(failed=0, attempted=66)
感谢您的帮助。
if __name__ == "__main__":
do_it()
我很惊讶 if __name__ == __main__:
没有给你关于未定义的错误 __main__
仅供参考,您将 self.prot.write(msg)
中的 port 拼错为 self.port.write(msg)
什么不是运行?它给出了什么错误?输出结果如何?
你为什么要 sys.exit(2)
?一个简单的 sys.exit()
就足够了。
此外,将 PORT = '/dev/ttyUSB0'
的变量设置为 PORT
可能会与 main() 函数中的 test_port = Serializer(port = PORT)
混淆。
我做了一个小 class 来打开 python 上的串行端口 (ttyUSB0),但是当我尝试 运行 它作为 main 它给了我很多我真的不知道的东西。
我希望 class 在我 运行 时创建一个串口实例,并让适当的函数(或方法)返回我对 [=32= 的要求] ]e的例子。相反,当我 运行:
时,我得到以下输出$ python3 entrada.py
我怎样才能运行如愿以偿?
这是 entrada.py
的代码import serial #for port opening
import sys #for exceptions
from collections import __main__
#
#configure the serial connections (the parameters differs on the device you are connecting to)
class Serializer:
def __init__(self, port, baudrate=9600, timeout=5):
self.port = serial.Serial(port = port, baudrate=baudrate,
timeout=timeout, writeTimeout=timeout)
def open(self):
''' Open the serial port.'''
self.port.open()
def close(self):
''' Close the serial port.'''
self.port.close()
def send(self, msg):
self.prot.write(msg)
def recv(self):
return self.port.readline()
PORT = '/dev/ttyUSB0' #Esto puede necesitar cambiarse
def main():
test_port = Serializer(port = PORT)
try:
test_port().open()
except:
print ("Could not open serial port: ", sys.exc_info()[0])
sys.exit(2)
while True:
print(test_port.recv())
if __name__ == __main__:
main()
这是输出:
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict
class Point(tuple):
'Point(x, y)'
__slots__ = ()
_fields = ('x', 'y')
def __new__(_cls, x, y):
'Create new instance of Point(x, y)'
return _tuple.__new__(_cls, (x, y))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new Point object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 2:
raise TypeError('Expected 2 arguments, got %d' % len(result))
return result
def _replace(_self, **kwds):
'Return a new Point object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('x', 'y'), _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % list(kwds))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + '(x=%r, y=%r)' % self
@property
def __dict__(self):
'A new OrderedDict mapping field names to their values'
return OrderedDict(zip(self._fields, self))
def _asdict(self):
'Return a new OrderedDict which maps field names to their values.'
return self.__dict__
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
def __getstate__(self):
'Exclude the OrderedDict from pickling'
return None
x = _property(_itemgetter(0), doc='Alias for field number 0')
y = _property(_itemgetter(1), doc='Alias for field number 1')
Point: x= 3.000 y= 4.000 hypot= 5.000
Point: x=14.000 y= 0.714 hypot=14.018
Point(x=100, y=22)
Point3D(x, y, z)
TestResults(failed=0, attempted=66)
感谢您的帮助。
if __name__ == "__main__":
do_it()
我很惊讶 if __name__ == __main__:
没有给你关于未定义的错误 __main__
仅供参考,您将 self.prot.write(msg)
中的 port 拼错为 self.port.write(msg)
什么不是运行?它给出了什么错误?输出结果如何?
你为什么要 sys.exit(2)
?一个简单的 sys.exit()
就足够了。
此外,将 PORT = '/dev/ttyUSB0'
的变量设置为 PORT
可能会与 main() 函数中的 test_port = Serializer(port = PORT)
混淆。