I'm new to python and have issues getting my code working.
I got two different modules, in module a.py I put all my methods, in module b.py I put the logic.
The development environment I'm using is 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")
Module 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()
Now to the issue:
When I run module b.py AFTER running a.py INSIDE Spyder everything is working as intended.
BUT: Spyder code analysis tells me
'a' imported but unused
When I try to call module b.py OUTSIDE Spyder I get following error
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
Importing configuration() with:
import a
a.configuration()
Gives following error:
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
I don't understand why my programm is running within spyder without problems but not outside.
Can someone help here?
You need to change module b to:
#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()
Related
I'm try to use RS232HAT With raspberry Pi 4 and I found this problem.
This is My code.
import serial
#print(serial.__file__)
dev = "/dev/ttySC0"
Baudrate = 115200
ser = serial.Serial(dev, Baudrate) <<< Stuck in this Function
print("START")
try:
while(1):
data = ser.read(value)
print(data.decode("utf-8"))
except KeyboardInterrupt:
print("EXIT")
exit()
When I interrupt by keyboard. The Program show this log.
Traceback (most recent call last):
File "/home/pi/Desktop/2-CH-RS232-HAT/python/examples/main.py", line 15, in <module>
ser = config.config(dev = "/dev/ttySC0")
File "/home/pi/Desktop/2-CH-RS232-HAT/python/lib/waveshare_2_CH_RS232_HAT/config.py", line 12, in __init__
ser.serial = serial.Serial(ser.dev, Baudrate)
File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 240, in __init__
self.open()
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 265, in open
self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
KeyboardInterrupt
My available devices:
you have to link the file, as example.
ln -s /dev/ttySC0 /dev/ttyS80
it sometimes cant read real serial info
I have this python code which getting data from socket's and printing to console. But in working process I getting this error code
Traceback (most recent call last):
File "server.py", line 1, in <module>
import ssl, socket
File "/home/ssl.py", line 20, in <module>
returned from time.time())
AttributeError: 'module' object has no attribute 'wrap_socket'
maybe somebody has any idea how I can fix this issue?
import ssl, socket
sock = ssl.wrap_socket(socket.socket(), 'server.key', 'server.crt', True)
sock.bind( ('', 443) )
sock.listen(10)
while True:
conn, addr = sock.accept()
data = conn.recv(4)
print data
thank you
You most likely have a file named ssl.py in the same directory, as indicated by this part of the error:
File "/home/ssl.py", line 20, in
returned from time.time())
and the script is trying to import that instead of the system level module. If you cannot change the name of that file, try using absolute and relative imports.
I have the following script:
#!/usr/bin/env python
import nxt.locator
from nxt.motor import *
def spin_around(b):
m_left = Motor(b, PORT_B)
m_left.turn(100, 360)
m_right = Motor(b, PORT_C)
m_right.turn(-100, 360)
print("Script Starting")
b = nxt.locator.find_one_brick()
spin_around(b)
I have installed pyUSB and libUSB. I run the script with python spin.py
However, when I run the script I get the following exception:
Script Starting
Traceback (most recent call last):
File "spin.py", line 14, in <module>
spin_around(b)
File "spin.py", line 8, in spin_around
m_left.turn(100, 360)
File "/Library/Python/2.7/site-packages/nxt/motor.py", line 211, in turn
raise BlockedException("Blocked!")
nxt.motor.BlockedException: Blocked!
Why is this exception occurring?
The script is making calls to motor ports "b" and "c".
If you do not have a motor plugged into port "b" or "c" then this exception will be caused.
To fix this error plug a motor into port "b" and another motor into port "c".
I have the following Python code:
import sys
import traceback
fifo_in = sys.argv[1]
while 1:
try:
exec open(fifo_in)
except:
traceback.print_exc()
sys.stdout.flush()
The first argument is a named pipe created by mkfifo. So the following prints '1':
mkfifo input
python script.py input
... in a separate terminal ...
echo "print 1" > input
Great, so far so good. But when I do something like echo "foobar" > input, the script only prints part of the traceback. It then pauses until I send it another command, and the output gets all mixed up:
echo "asdf" > input # pause here and check output
echo "print 1" > input
... in output terminal ...
Traceback (most recent call last):
File "test.py", line 8, in <module>
exec open(fifo_in)
File "in", line 1, in <module>
...PAUSES HERE...
print 1
NameError: name 'asdf' is not defined
What's going on? How can I get stdout to flush fully and why is it out of order? I've tried using traceback.format_exc instead, then printing it by hand, but I get the same result. Calling sys.stderr.flush does not fix anything either. I've also tried putting a sleep in the loop to see if that helps, but nothing.
UPDATE
One interesting piece of behavior I am seeing: If I ctrl+c it, normally the program keeps running - the try/except just catches the KeyboardInterrupt and it keeps looping. However, if I ctr+c it after sending it an error, the program exits and I get the following. It's almost like it pauses inside of print_exc:
^CTraceback (most recent call last):
File "test.py", line 10, in <module>
traceback.print_exc()
File "/usr/lib/python2.7/traceback.py", line 232, in print_exc
print_exception(etype, value, tb, limit, file)
File "/usr/lib/python2.7/traceback.py", line 125, in print_exception
print_tb(tb, limit, file)
File "/usr/lib/python2.7/traceback.py", line 69, in print_tb
line = linecache.getline(filename, lineno, f.f_globals)
File "/usr/lib/python2.7/linecache.py", line 14, in getline
lines = getlines(filename, module_globals)
File "/usr/lib/python2.7/linecache.py", line 40, in getlines
return updatecache(filename, module_globals)
File "/usr/lib/python2.7/linecache.py", line 132, in updatecache
with open(fullname, 'rU') as fp:
KeyboardInterrupt
I think you want to look at the stdlib code module
This behavior is from using exec. Exec is for evaluating python code so "print 1" executes the python code print 1, where as "asdf" will raise a NameError as it does not exist in the context. exec open(fifo_in) is strange as it shouldn't work. The while will also eat up 100% cpu.
UPDATE: fix sleep duration
Here is a modified version of your code to try.
import sys
import time
import traceback
fifo_in = sys.argv[1]
try:
fp = open(fifo_in) # will block until pipe is opened for write
except IOError:
traceback.print_exc()
except OSError:
traceback.print_exc()
data = None
while True:
try:
data = fp.read()
try:
exec data
except:
traceback.print_exc()
finally:
time.sleep(0.1)
except KeyboardInterrupt:
break
I am trying to connect to some router using the above code and I am using juniperj2320.py module and in test file I have
am using code base from this http://subversion.assembla.com/svn/clauzsistel08/trunk/dist/
#!/usr/bin/python
from localconf import *
from juniperj2320 import *
import sys
import traceback
SERIALDEVICE = '/dev/ttyUSB0'
# Now configure the router
try:
router = JuniperJ2320(SERIALDEVICE)
except RouterConfigurationException, err:
print "Router configuration error: ", err
print "Please try again."
sys.exit(1)
but am getting this following error
./test.py
> /root/pyserial-2.6/examples/serialrouter.py(37)__init__()
-> serial.Serial.__init__(self, serialdevice, baudrate=baudrate, \
(Pdb) c
Traceback (most recent call last):
File "./test.py", line 30, in
router = JuniperJ2320(SERIALDEVICE)
File "/root/pyserial-2.6/examples/juniperj2320.py", line 32, in __init__
BYTESIZE, PARITY, STOPBITS, TIMEOUT)
File "/root/pyserial-2.6/examples/serialrouter.py", line 44, in __init__
fdpexpect.fdspawn.__init__(self, self.fileno())
File "/usr/lib/python2.6/site-packages/fdpexpect.py", line 40, in __init__
spawn.__init__(self, None, args, timeout, maxread, searchwindowsize, logfile )
File "/usr/lib/python2.6/site-packages/pexpect.py", line 412, in __init__
self.closed = True # File-like object.
AttributeError: can't set attribute
and absolutely clue less on wat happening here ! any help ll be greatly appreciated
thanks
This is a little bit of a shot in the dark, because I'm not familiar with the modules you're using, but based on the traceback, it looks like the constructor is expecting a file-like object, not just a file path. Try this instead.
SERIALDEVICE = '/dev/ttyUSB0'
# Now configure the router
try:
router = JuniperJ2320(open(SERIALDEVICE))
Instead of writing your own serial communications program wouldn't be easier to have pexpect drive a serial program like minicom?