Valor = 1234
str(1234)
print(("Valor: %s")%Valor)
print("Valor: "+str(Valor))
python prueba.py
import os
os.__doc__
print(os.__doc__)
>>> os.__doc__
"OS routines for NT or Posix depending on what system we're on.\n\nThis exports:\n - all functions from posix, nt or ce, e.g. unlink, stat, etc.\n - os.path is either posixpath or ntpath\n - os.name is either 'posix', 'nt' or 'ce'.\n - os.curdir is a string representing the current directory ('.' or ':')\n - os.pardir is a string representing the parent directory ('..' or '::')\n - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\\\')\n - os.extsep is the extension separator (always '.')\n - os.altsep is the alternate pathname separator (None or '/')\n - os.pathsep is the component separator used in $PATH etc\n - os.linesep is the line separator in text files ('\\r' or '\\n' or '\\r\\n')\n - os.defpath is the default search path for executables\n - os.devnull is the file path of the null device ('/dev/null', etc.)\n\nPrograms that import and use 'os' stand a better chance of being\nportable between different platforms. Of course, they must then\nonly use functions that are defined by all platforms (e.g., unlink\nand opendir), and leave all pathname manipulation to os.path\n(e.g., split and join).\n"
>>> print(os.__doc__₎
OS routines for NT or Posix depending on what system we're on.
This exports:
- all functions from posix, nt or ce, e.g. unlink, stat, etc.
- os.path is either posixpath or ntpath
- os.name is either 'posix', 'nt' or 'ce'.
- os.curdir is a string representing the current directory ('.' or ':')
- os.pardir is a string representing the parent directory ('..' or '::')
- os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
- os.extsep is the extension separator (always '.')
- os.altsep is the alternate pathname separator (None or '/')
- os.pathsep is the component separator used in $PATH etc
- os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
- os.defpath is the default search path for executables
- os.devnull is the file path of the null device ('/dev/null', etc.)
Programs that import and use 'os' stand a better chance of being
portable between different platforms. Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
import os
import sys
sys.path.append('..')
print(os.listdir(sys.path[-1]))
$ pwd
/home/alex/proyectos/python/tests
$ python3 test1.py
['tests', 'ANU', 'hashtables_tests']
$ cd ..
$ python3 tests/test1.py
['wimdAPI', 'MicrochipData', 'RaspberryPi', 'arm_ide', 'au', '.gitignore', 'Cordova', 'MSP340', 'Electron', 'nodejs', 'repuve', 'Pomodoro', 'cloud', 'python', 'RecyBot', 'electron', 'libs', 'microcontrollers', 'wave', 'RealTime', 'mosquitto', 'MonitorS', '.git', '8051', 'ghdl', 'games', 'TestM', 'Ada', 'OpenERP', 'Odoo', 'esp8266', 'ARMIDE', 'PCBExample', 'VHDL', 'BMLP', 'TivaC', 'FacturaSAT']
import os
import sys
#sys.path.append('..')
#print(os.listdir(sys.path[-1]))
#print(sys.path[-1])
print(__file__)
print(os.path.abspath(__file__))
$ python3 tests/test1.py
tests/test1.py
$ cd tests
$ python3 test1.py
test1.py
/home/alex/proyectos/python/tests/test1.py
import os
import sys
#sys.path.append('..')
#print(os.listdir(sys.path[-1]))
#print(sys.path[-1])
print(__file__)
print(os.path.abspath(__file__))
print(os.path.dirname(os.path.abspath(__file__))
$ python3 test1.py
test1.py
/home/alex/proyectos/python/tests/test1.py
/home/alex/proyectos/python/tests
$ cd ..
$ python3 tests/test1.py
tests/test1.py
/home/alex/proyectos/python/tests/test1.py
/home/alex/proyectos/python/tests
import os
import sys
file_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(file_dir,'..'))
print(sys.path[-1])
print(os.listdir(sys.path[-1]))
$ python3 tests/test1.py
/home/alex/proyectos/python/tests/..
['tests', 'ANU', 'hashtables_tests']
$ cd tests
$ python3 test1.py
/home/alex/proyectos/python/tests/..
['tests', 'ANU', 'hashtables_tests']
...
y este es el resultado:Código: Python
DEBUG: Serial<id=0x7ff6a6dbef98, open=False>(port=None, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False)
Saludos!
Código: Python
#!/usr/bin/env python3.5 # -*- coding: utf-8 -*- import serial #import sys class Puerto(object): def __init__(self, port, baudrate, timeout): super(Puerto, self).__init__() self.port = port self.baudrate = baudrate self.timeout = timeout def open_port(self): try: sg = serial.Serial() print(('DEBUG: ' + str(sg))) except serial.SerialException: print(('Error al abrir el puerto ' + self.port)) def msg(self): print(('\n' + self.port + ' is open...')) print(('baudrate ' + str(self.baudrate))) print(('timeout ' + str(self.timeout)))
Para probarlo hago lo siguiente igual me equivoco:Código: Python
from prueba_clase import* puerto = Puerto('/dev/ttyUSB0', 9600, 1.0) puerto.open_port()
y este es el resultado:Código: Python
DEBUG: Serial<id=0x7ff6a6dbef98, open=False>(port=None, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False)
import serial
#Abrir puerto, default = 9600,8,N,1.
#Al pasarle puerto ya hace el open?, si no le paso nada no lo hace?
ser = serial.Serial('/dev/ttyUSB0') # open serial port
print(ser.name) # check which port was really used
#Escribir puerto
ser.write(b'hello') # write a string
#Leer
x = ser.read() # read one byte
s = ser.read(10) # read up to ten bytes (timeout)
line = ser.readline() # read a '\n' terminated line
#Cerrar
ser.close() # close port
#Ahora que está cerrado es seguro cambiar baudrate, paridad, etc
#No cambiaría esos parámetros mientras el puerto está abierto, por las dudas.
sg = serial.Serial()
sg = serial.Serial(port=self.port,baudrate=self.baudrate,timeout=self.timeout)
super(Puerto, self).__init__()
No es necesariosg = serial.Serial(self, port, baudrate, timeout)Seríasg = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout)class Serial(RawDriver):
""" Define Serial printer """
def __init__(self, **kwargs):
"""
@param devfile : Device file under dev filesystem
@param baudrate : Baud rate for serial transmission
@param bytesize : Serial buffer size
@param timeout : Read/Write timeout
"""
if "devfile" in kwargs:
self.devfile = kwargs["devfile"]
else:
self.devfile = "/dev/ttyS0"
if "baudrate" in kwargs:
self.baudrate = int(kwargs["baudrate"])
else:
self.baudrate = 9600
if "bytesize" in kwargs:
self.bytesize = int(kwargs["bytesize"])
else:
self.bytesize = 8
if "timeout" in kwargs:
self.timeout = int(kwargs["timeout"])
else:
self.timeout = 1
#self.barcode = barcode
#self.dpi = 180
self.open()
def open(self):
""" Setup serial port and set is as escpos device """
self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate, bytesize=self.bytesize, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=self.timeout, dsrdtr=True)
if self.device is not None:
print "Serial printer enabled"
else:
print "Unable to open serial printer on: %s" % self.devfile
class RawDriver(BaseDriver):
def __init__(self):
pass
def _raw(self,msg,end=True):
if hasattr(self.device,"write"):
self.device.write(msg)
elif hasattr(self.device,"send"):
self.device.send(msg)
class BaseDriver(object):
dtype = None #Driver type OSDriver, RawDriver
device = None
def open(self):
pass
def _raw(self,msg,end=True):
pass
def __del__(self):
if self.device:
self.device.close()
self.device = None
class Serial(object):
device = None
def __init__(self, **kwargs):
"""
@param devfile : Device file under dev filesystem
@param baudrate : Baud rate for serial transmission
@param bytesize : Serial buffer size
@param timeout : Read/Write timeout
"""
if "devfile" in kwargs:
self.devfile = kwargs["devfile"]
else:
self.devfile = "/dev/ttyS0"
if "baudrate" in kwargs:
self.baudrate = int(kwargs["baudrate"])
else:
self.baudrate = 9600
if "bytesize" in kwargs:
self.bytesize = int(kwargs["bytesize"])
else:
self.bytesize = 8
if "timeout" in kwargs:
self.timeout = int(kwargs["timeout"])
else:
self.timeout = 1
#self.barcode = barcode
#self.dpi = 180
self.open()
def open(self):
""" Setup serial port and set is as escpos device """
self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate, bytesize=self.bytesize, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=self.timeout)
if self.device is not None:
print "Serial printer enabled"
else:
print "Unable to open serial printer on: %s" % self.devfile
def send(self,msg):
self.device.write(msg)
def read(self,nBytes=1):
return self.device.read(nBytes);
def readline(self):
return self.device.readline()
def close(self):
if self.device is not None:
self.device.close()
self.device = None
def __del__(self):
self.close()
ser = Serial(devfile="/dev/ttyUSB0",baudrate=9600, bytesize=8)
ser.open()
ser.read()
ser.readline()
ser.close()