By "random" I think you mean "arbitrary", i.e. how to send an arbitrary number of bytes...
You can generate a sequence of repeating digits like this:
>>> ''.join([str(i%10) for i in range(21)]) '012345678901234567890'
The number of bytes required can be passed to the script as a command line argument. Its value will be available in the sys.argv[] list.
import sys import serial try: num_bytes = int(sys.argv[1]) except (IndexError, ValueError): sys.stderr.write('Usage: {} num-bytes\n'.format(sys.argv[0])) sys.exit(1) ser = serial.Serial() # set up your serial port digits = ''.join(str(i%10) for i in range(num_bytes)) num_written = ser.write(bytes(digits, 'ascii'))
Invoke the command like this:
$ python3 send_bytes.py 42