python 的 subprocess 如何像 shell 一样,和终端可以多次交互操作?

python 的 subprocess 如何像 shell 一样,和终端可以多次交互操作?

比如我编写一个这样的 shell 脚本

图片.png

然后在终端执行

图片.png

我就能获得一个『交互式』的『东西』

我想用 python 也实现,但是发现不行

import subprocess

process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while True:
    cmd = input("$ ")
    if cmd == "exit":
        break
    cmd = cmd.encode('utf-8')
    
    print('cmd',cmd)
    process.stdin.write(cmd)
    process.stdin.flush()
    output = process.stdout.readline().decode('utf-8')
    print(output.strip())

图片.png

输入后就是卡死,没有任何反应,怎么办?

阅读 4k
1 个回答

你的代码的问题可能是你没有在每个命令后面加上换行符,导致bash无法识别命令的结束。你可以尝试在cmd后面加上b’\n’,我改了一下代码,你可以看看:

import subprocess

process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while True:
    cmd = input("$ ")
    if cmd == "exit":
        break
    cmd = cmd.encode('utf-8') + b'\n'
    
    print('cmd',cmd)
    process.stdin.write(cmd)
    process.stdin.flush()
    output = process.stdout.readline().decode('utf-8')
    print(output.strip())
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题