TAGS :Viewed: 2 - Published at: a few seconds ago

[ Communicate with subprocess by sending int data ]

I am using subprocess.Popen to launch a new program which expects int data from stdin.

proc = Popen('command', shell=False,stdout=PIPE, stdin=PIPE, stderr=STDOUT)
proc.communicate(1)

Got error as

TypeError: 'int' object is unsubscriptable

Can we have any other way out by which I can launch a new program and pass int data?

Answer 1


As it says here:

The optional input argument should be a string to be sent to the child process

so you will have to send '1' and then convert it in your program

Answer 2


The argument to Popen.communicate() must be a bytes or a str object. This should work in both Python 2.x and 3.x:

proc.communicate(b'1')

or using a variable:

proc.communicate(str(myint).encode())

For the ​sake of completeness, to send an actual integer instead of it's ASCIIfication, you could do:

proc.communicate(bytes(bytearray([myint])))