shell 使用脚本传递初始值,但在终端中与程序保持交互

t30tvxxf  于 2023-08-07  发布在  Shell
关注(0)|答案(1)|浏览(93)

以下是我的互动程序:

import sys

print ("what's your name?")

sys.stdout.write("> ")
sys.stdout.flush()

for line in sys.stdin:
    line = line.rstrip()

    if line == "q":
        break

    print ("hello", line)

    sys.stdout.write("> ")
    sys.stdout.flush()

字符串
它在一个循环中运行:

$ python3 name.py
what's your name?
> tom
hello tom
> john
hello john


我想要的是最初传递输入,在本例中是name,但能够进一步与程序交互。
到目前为止我得到的是

#! /bin/bash

echo "mr. big" | python3 name.py


但是,这会运行程序并立即退出:

$ ./script
what's your name?
> hello mr. big
> $

gcuhipw9

gcuhipw91#

这就是你想做的吗?

的数据

#!/bin/bash

(echo "mr. big"; cat) | python3 test.py

字符串
在您的脚本echo "mr. big" | python3 name.py中,输入直接从echo命令通过管道传输到您的python脚本。这意味着echo在您提供的第一个值之后关闭输入,并终止脚本。
这里使用(echo "mr. big"; cat) | python3 name.py子shell,它首先回显初始值“mr”。big”,然后使用cat从程序中读取更多的用户输入。本质上,您是将子shell的输出通过管道传输到Python脚本,该脚本保持输入打开以进行持续的交互。

相关问题