Re: Python talks to a tty port... how?

Tako Schotanus (sst@bouw.tno.nl)
Wed, 12 Apr 1995 08:11:37 GMT

In article <GRENDEL.95Apr11161846@fen.arc.nasa.gov>, grendel@fen.arc.nasa.gov (Raymond E. Suorsa) says:
>
>
>I would like to replace some old C code with Python. This old C code
>opens up a /dev/tty and then sets the parity, stop bits, etc etc...
>
>If you could show me how to write replace these two functions with
>some slick Python code I and all my descendants will revere your name
>with rituals and moments-of-silence for all time... well, a couple
>days at least. :-)

Wow! My birthday already is a national holiday and now I'm going to have my
own group of worshippers? ;)

>
>int ttyopen(VideoUnit *V)
>{
> char command[80];
>
> strcpy(command,"stty 9600 -parenb cs8 -cstopb raw -echo > ");
> strcat(command,V->ttyport);
>
> if ((V->handel = open(V->ttyport, O_RDWR)) == -1)
> {
> printf("ERROR: cannot open %s\n",V->ttyport);
> return(1);
> }
>
> if (system(command))
> {
> printf ("\nERROR: The port was NOT initialized.\n");
> printf ("Please see that the protection on %s is lifted.\n",V->ttyport);
> return(1);
> }
>
> /* flush the port */
> (void)ioctl(V->handel, TCFLSH, 0);
>
> return(0);
>}
>

import posix, fcntl, FCNTL

def ttyopen(V) :
command = "stty 9600 -parenb cs8 -cstopb raw -echo > " + V.ttyport
V.handle = posix.open(V.ttyport, FCNTL.O_RDWR)
if V.handle == -1 :
print "ERROR: cannot open " + V.ttyport
return 1
if posix.system(command) :
print "ERROR: The port was NOT initialized."
print "Please see that the protection on " + V.ttyport + "is lifted."
return 1
fcntl.ioctl(V.handle, FCNTL.TCFLSH, 0)
return 0

>
>ttywrite(VideoUnit *V, char *out_string)
>{
> int len;
>
>
> len = strlen(out_string);
>
> if (write(V->handel, out_string, len) != len) {
> printf("ERROR in ttywrite: Unable to write to device!\n");
> return(1);
> }
>
> return(0);
>}

def ttywrite(V, out_string) :
len = len(out_string)
if posix.write(V.handle, out_string, len) != len :
print "ERROR in ttywrite: Unable to write to device!"
return 1
return 0

I think this should work. Of course it might be possible to use Python's own file-objects
but at least this way I'm sure you get the same behaviour as the C-code. I expect you to
be able to write your own V-structure (use a class).
NB: If you don't like all those posix.blahblah and fcntl.blahblah calls you can of course
use import * from posix to get rid of all that

Hope this helps (no guarantees :)

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
_/ Tako Schotanus TNO Building and Construction Research _/
_/ Phone : +31 15 842393 Fax : +31 15 122182 E-mail : sst@bouw.tno.nl _/
_/ My employer is required,by Dutch law,to disagree with whatever I say _/
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/