On a Debian Linux system I have a Python script that prepares a string to be written out to a USB CDC device at /dev/ttyACM0. This write occurs at the end of the script as follows...
USBpipe = open("/dev/ttyACM0", 'w')
shellCmd = subprocess.Popen(["echo", USBpacket], stdout = USBpipe)
USBpipe.close()
...where USBpacket is a string. If I make this a pure string such as using USBpacket = "test" the code executes correctly and I've verified the data appears on the USB device. However, during normal execution USBpacket gets bytes appended to it via the chr() function, and some of these may be zero. When this happens I get this error running the script:
Traceback (most recent call last):
File "/root/gpstoPIC.py", line 247, in <module>
shellCmd = subprocess.Popen(["echo", USBpacket], stdout = USBpipe)
File "/usr/lib/python3.9/subprocess.py", line 951, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.9/subprocess.py", line 1756, in _execute_child
self.pid = _posixsubprocess.fork_exec(
ValueError: embedded null byte
I've tried a couple of solutions that haven't worked, such as doing wb instead of w on the open of /dev/ttyACM0, and using bytes() to convert from string to binary. What is the correct way to write out this data?
echoinstead ofUSBpipe.write(USBpacket)? Wouldn't that be simpler?echowas the only thing that I got to work, so when I was ready to write a script and not just test direct from the shell that's what I used. However, after reading your comment I ditched usingsubprocessand usedwrite()instead and it was just fine. Since this was stated in a comment and not an official answer I picked the other post here as an answer even though it repeats what you said (along with some extraneous information).