通过发送 int 数据与子进程通信
Communicate with subprocess by sending int data
我正在使用 subprocess.Popen
启动一个需要来自标准输入的 int 数据的新程序。
proc = Popen('command', shell=False,stdout=PIPE, stdin=PIPE, stderr=STDOUT)
proc.communicate(1)
出现错误
TypeError: 'int' object is unsubscriptable
我们可以有任何其他方法来启动新程序并传递 int 数据吗?
如其所说here:
The optional input argument should be a string to be sent to the child
process
所以你必须发送 '1'
然后在你的程序中转换它
Popen.communicate()
的参数必须是 bytes
或 str
对象。这应该适用于 Python 2.x 和 3.x:
proc.communicate(b'1')
或使用变量:
proc.communicate(str(myint).encode())
为了完整起见,要发送一个实际的整数而不是它的 ASCIIfication,你可以这样做:
proc.communicate(bytes(bytearray([myint])))
我正在使用 subprocess.Popen
启动一个需要来自标准输入的 int 数据的新程序。
proc = Popen('command', shell=False,stdout=PIPE, stdin=PIPE, stderr=STDOUT)
proc.communicate(1)
出现错误
TypeError: 'int' object is unsubscriptable
我们可以有任何其他方法来启动新程序并传递 int 数据吗?
如其所说here:
The optional input argument should be a string to be sent to the child process
所以你必须发送 '1'
然后在你的程序中转换它
Popen.communicate()
的参数必须是 bytes
或 str
对象。这应该适用于 Python 2.x 和 3.x:
proc.communicate(b'1')
或使用变量:
proc.communicate(str(myint).encode())
为了完整起见,要发送一个实际的整数而不是它的 ASCIIfication,你可以这样做:
proc.communicate(bytes(bytearray([myint])))