2

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?

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
AlokThakur
  • 3,599
  • 1
  • 19
  • 32

2 Answers2

0

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

eli
  • 490
  • 1
  • 3
  • 22
0

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])))
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • 2
    on *"send an actual integer"*: ascii representation is not less "actual" than e.g., [`myint.to_bytes((myint.bit_length() + 7) // 8, 'big')` serialization for unsigned values](http://stackoverflow.com/a/28524760/4279). Human-readable representation should be preferable for exchanging data between processes unless you have a reason not to do it (e.g., due to performance, legacy apps). Note: your code `bytes(bytearray([myint]))` works only for `myint` in `range(0, 256)`, you could use `struct.pack('B', myint)` to make it explicit. – jfs Feb 04 '16 at 14:52