0

I tries to grab a uart - line and give this string to a shell script;

#!/usr/bin/env python
import os
import serial

ser = serial.Serial('/dev/ttyAMA0', 4800)
while True :
 try:
    state=ser.readline()
    print(state)
 except:
    pass

So, "state" should given to a shell script now, like: myscript.sh "This is the serial input..." but how can I do this?

print(os.system('myscript.sh ').ser.readline())

doesn't work.

dokle
  • 3
  • 1
  • `os.system()` doesn't return anything you want to `print`. If the subprocess prints anything to standard output, that's where it'll go, and your Python script won't know. If you want to capture what the subprocess prints, you have yet another reason to look at the `subprocess` module instead, specifically the `check_output` method (Python 2.7+) – tripleee Jul 25 '16 at 15:01

3 Answers3

0

There are different ways to combine two strings (namely "./myscript.sh" and ser.readLine()), which will then give you the full command to be run by use of os.system. E.g. strings can be arguments of the string.format method:

os.system('myscript.sh {}'.format(ser.readline()))

Also you can just add two strings:

os.system('myscript.sh '+ser.readline())

I am not sure what you want to achieve with the print statement. A better way to handle the call and input/output of your code would be to switch from os to the subprocess module.

jotasi
  • 5,077
  • 2
  • 29
  • 51
0

Just simple string concatenation passed to the os.system function.

import os
os.system("myscript.sh " + ser.readline())
0

If myscript can continuously read additional input, you have a much more efficient pipeline.

from subprocess import Popen, PIPE
sink = Popen(['myscript.sh'], stdin=PIPE, stdout=PIPE)
while True:
    sink.communicate(ser.readline())

If you have to start a new myscript.sh for every input line, (you'll really want to rethink your design, but) you can, of course:

while True:
    subprocess.check_call(['myscript.sh', ser.readline())

Notice how in both cases we avoid a pesky shell.

Community
  • 1
  • 1
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thanks, - yes, I'd start a new script for each input line, because there are only few lines a day and I need the ability to change the process script, without interrupt the read - line process, so since 5 years ago, I decided to made two scripts, one for reading and one for testing the lines. But the shell script for reading doesn't worked at the new hw (pi 3), so I'm searching a new "reading" script, now. – dokle Jul 25 '16 at 14:54