Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm having a problem where I get errors when I try 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 changed the way it handles strings but I dont understand how to format the 'message'. Does anyone know how I'd change this code to be valid?

many thanks

jon

update: heres the 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
like image 723
jonathan topf Avatar asked Dec 13 '11 09:12

jonathan topf


People also ask

How do I format a string in Python 3?

Method 2: Formatting string using format() method Format() method was introduced with Python3 for handling complex string formatting more efficiently. Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str. format().

What is %d and %f in Python?

For example, "print %d" % (3.78) # This would output 3 num1 = 5 num2 = 10 "%d + %d is equal to %d" % (num1, num2, num1 + num2) # This would output # 5 + 10 is equal to 15. The %f formatter is used to input float values, or numbers with values after the decimal place.

What is format () in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.


2 Answers

If you have a string variable that you want to write to a pipe (and not a bytes object), you have two choices:

  1. Encode the string first before you write it to the pipe:
working_file.stdin.write('message'.encode('utf-8'))
  1. Wrap the pipe into a buffered text interface that will do the encoding:
stdin_wrapper = io.TextIOWrapper(working_file.stdin, 'utf-8')
stdin_wrapper.write('message')

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

like image 152
Seppo Enarvi Avatar answered Sep 29 '22 20:09

Seppo Enarvi


Is your error message "TypeError: 'str' does not support the buffer interface"? That error message tells you pretty much exactly what is wrong. You don't write string objects to that sdtin. So what do you write? Well, anything supporting the buffer interface. Typically this is bytes objects.

Like:

working_file.stdin.write(b'message')
like image 25
Lennart Regebro Avatar answered Sep 29 '22 22:09

Lennart Regebro