martiert
martiert

Reputation: 1686

How to read from the serial port in python without using external APIs?

I have to read a stream which is sent from a homemade device over the serial port. The problem is that it should be deployed on a machine where I don't have access to install anything new, which means I have to use the python standard libraries to do this. Is this possible, and if so, how can I manage this.

If it turns out to be almost impossible, I will have to get someone to install pySerial, but I would really appreciate it if it could be done without this.

If there is differences in Linux/Windows, this is on a Windows machine, but I would really appreciate a cross platform solution.

Upvotes: 6

Views: 6476

Answers (2)

Ian Goldby
Ian Goldby

Reputation: 6174

You say you don't have access to install anything new. I'm guessing it is a permissions issue - i.e. you can't obtain elevated administration access and pip install/conda install fails.

If you have any kind of normal user login access to the machine (which I presume you must have either directly or indirectly in order to put your script on to the machine in the first place) then you can use a virtual environment to install the modules that you need. This can all be done from a normal user account.

Just Google for "python virtual environment" and you'll find all you need.

If you are using Anaconda Python it's slightly different. Google for "conda environment".

If you can't even obtain a command prompt on the host PC - e.g. you zip up the files and give them to someone else to deploy - you can still use a virtual environment. You'll just have to zip up the virtual environment along with your script. With Anaconda you can arrange for the environment to be created in the same directory as your project by using the -p switch. I presume pipenv has something similar.

Or you could package everything up with pyinstaller, which creates a stand-alone runtime with all the modules included.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 993085

On Unix-like operating systems, the serial port work just like a file, and you simply open it and read or write bytes. There are some extra calls you can make to set the baud rate and whatnot, but that's essentially all there is.

On Windows, you open the serial port like a file, but you must use some particular ways of accessing it that are slightly different from what Python uses for normal files. Unfortunately it is difficult to successfully access a Windows serial port using only native Python libraries.

The pyserial library provides a uniform, cross-platform way of accessing serial ports. It relies on ctypes, which is in the standard library since Python 2.5, so you may be able to include pyserial with your application and just use that.

Upvotes: 7

Related Questions