String formatting for stdin.write () in python 3.x

I got a problem when I get errors while trying to execute this code with python 3.2.2

working_file = subprocess.Popen(["/pyRoot/iAmAProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) working_file.stdin.write('message') 

I understand that python 3 has changed the way strings are handled, but I don't understand how to format a "message". Does anyone know how I can change this code to be valid?

many thanks

John

update: heres error message i get

 Traceback (most recent call last): File "/pyRoot/goRender.py", line 18, in <module> working_file.stdin.write('3') TypeError: 'str' does not support the buffer interface 
+6
source share
2 answers

Is your error message "TypeError:" str "does not support the buffer interface"? This error message tells you pretty much what is wrong. You are not writing string objects to this sdtin. So what are you writing? Well, everything that supports a buffer interface. These are usually byte objects.

how

 working_file.stdin.write(b'message') 
+2
source

I agree with the previous answer (except that the "error message tells you exactly what is wrong"), but I would like to complete it. If the fact is that you have a string that you want to write to the channel (and not a byte object), you have two options:

1) First encode each line before writing them to the channel:

 working_file.stdin.write('message'.encode('utf-8')) 

2) Wrap the handset in a buffer text interface that will perform encoding:

 stdin_wrapper = io.TextIOWrapper(working_file.stdin, 'utf-8') stdin_wrapper.write('message') 

(Note that I / O is now buffered, so you may need to call stdin_wrapper.flush ().)

+7
source

Source: https://habr.com/ru/post/903662/


All Articles