简体   繁体   中英

Unable to execute Ruby script from file, but IRB works fine?

I have a tiny shell script that writes to a serial device:

#!/usr/bin/ruby

require 'rubygems'
require 'serialport'

@sp = SerialPort.new "/dev/tty.usbserial-A6004cNN", 19200
@sp.write ["\x01\x01\x04\x00", "n", "\xff\xff\xff"]

This doesn't write to the serial device when I run ./script.sh in that directory. However when I jump into IRB and run:

require 'serialport' #=> true
@sp = SerialPort.new "/dev/tty.usbserial-A6004cNN", 19200 #=> #<SerialPort:0x1016bd698>
@sp.write ["\x01\x01\x04\x00", "n", "\xff\xff\xff"] #=> 8

This way works... I'm baffled. Could it be the way i'm outputting my byte array? That doesn't seem right, its just raw ruby here, doesn't have an dependancies that are obvious. Also the script doesn't throw an exception, it executes just fine, however the device just doesn't respond.

How would I go about debugging this? I'm not sure where to start.

I don't know the SerialPort gem, but it's possible that output to the serial port is being buffered, and not flushed before the script exits, while IRB gives it time to flush the buffer as you go back to a prompt. I'd try adding @sp.flush and see if that helps at all.

Instead of having it be a shell script, make it a .rb ruby script, then call it with

ruby <name_of_my_script>.rb

Then everything should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM