使用popen和专用的TTY Python运行交互式Bash

我需要使用自己的专用TTY在Python的单独进程中运行交互式Bash实例(我不能使用pexpect)。我使用了类似程序中常见的代码片段:

master, slave = pty.openpty()

p = subprocess.Popen(["/bin/bash", "-i"], stdin=slave, stdout=slave, stderr=slave)

os.close(slave)

x = os.read(master, 1026)

print x

subprocess.Popen.kill(p)

os.close(master)

但是当我运行它时,我得到以下输出:

$ ./pty_try.py

bash: cannot set terminal process group (10790): Inappropriate ioctl for device

bash: no job control in this shell

运行的轨迹显示一些错误:

...

readlink("/usr/bin/python2" title="python2">python2.7", 0x7ffc8db02510, 4096) = -1 EINVAL (Invalid argument)

...

ioctl(3, SNDCTL_TMR_TIMEBASE or SNDRV_TIMER_IOCTL_NEXT_DEVICE or TCGETS, 0x7ffc8db03590) = -1 ENOTTY (Inappropriate ioctl for device)

...

readlink("./pty_try.py", 0x7ffc8db00610, 4096) = -1 EINVAL (Invalid argument)

该代码段看起来非常简单,Bash是否没有得到所需的东西?这可能是什么问题?

回答:

这是最后对我有用的解决方案(由qarma建议):

libc = ctypes.CDLL('libc.so.6')

master, slave = pty.openpty()

p = subprocess.Popen(["/bin/bash", "-i"], preexec_fn=libc.setsid, stdin=slave, stdout=slave, stderr=slave)

os.close(slave)

... do stuff here ...

x = os.read(master, 1026)

print x

以上是 使用popen和专用的TTY Python运行交互式Bash 的全部内容, 来源链接: utcz.com/qa/411045.html

回到顶部