Python中如何在Jupyter notebook中运行命令行交互式代码并实现自动响应

比如说我需要调用一个下载数据的函数,但是这个函数会在命令行询问是否下载,需要输入 Y/n,在 jupyter 中直接就 EOF 异常了,我也尝试去往缓冲区写东西,但是方法并没有响应,是否有魔法命令解决这个问题呢
Python中如何在Jupyter notebook中运行命令行交互式代码并实现自动响应

4 回复

jupyter 理论上是支持 shell 交互的啊,贴下代码吧


在Jupyter notebook里运行命令行交互式代码并自动响应,可以用subprocess模块的Popen配合communicate方法。下面是个完整示例:

import subprocess
import time

# 要执行的命令
cmd = ["python", "-c", "name = input('Enter your name: '); print(f'Hello, {name}!')"]

# 创建子进程
proc = subprocess.Popen(
    cmd,
    stdin=subprocess.PIPE,  # 允许向进程输入
    stdout=subprocess.PIPE,  # 捕获输出
    stderr=subprocess.PIPE,
    text=True,  # 使用文本模式
    bufsize=1  # 行缓冲
)

# 自动响应输入
response = "Alice\n"
output, error = proc.communicate(input=response, timeout=5)

print("输出:", output)
if error:
    print("错误:", error)

关键点:

  1. stdin=subprocess.PIPE 让你能向进程发送输入
  2. communicate() 方法会等待进程结束,并发送你提供的输入
  3. 输入内容需要包含换行符 \n 来模拟回车

更复杂的交互场景: 如果命令需要多次交互,可以用proc.stdin.write()proc.stdout.readline()循环处理:

proc = subprocess.Popen(
    ["python", "-c", """
for i in range(3):
    ans = input(f'Question {i+1}: ')
    print(f'You said: {ans}')
"""],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    text=True
)

responses = ["First\n", "Second\n", "Third\n"]
output_lines = []

for resp in responses:
    proc.stdin.write(resp)
    proc.stdin.flush()
    time.sleep(0.1)  # 给进程处理时间
    line = proc.stdout.readline()
    output_lines.append(line.strip())

proc.stdin.close()
full_output = proc.stdout.read()
print("\n".join(output_lines))

注意: 对于某些需要终端特性的程序(如vimtop),可能需要用pty模块,但在Jupyter里这通常比较麻烦。

简单说就是subprocess.Popencommunicate搞定自动响应。

不好意思,刷新了一下,又运行了一遍可以了,可能是我 jupyter 不是跑在本地的,有些 js 没加载上,谢谢了

了解,没事

回到顶部