简体   繁体   English

Output 的交互式 python 到 shell 变量

[英]Output of interactive python to shell variable

There is an interactive python script something like有一个交互式 python 脚本类似于

def myfunc():
    print("enter value between 1 to 10")
    i=int(input())
    if(i<1 or i>10):
        print("again")
        myfunc()
    else:
        print(i)

I want to store the final output which is print(i) in a shell variable.我想将最终的 output print(i)存储在 shell 变量中。 Something like就像是

python myFile.py | read a

Above query get stuck everytime i run the command.每次我运行命令时,上面的查询都会卡住。 Is it possible to do that?有可能这样做吗? Even though ( read b | python myFile.py ) | read a即使( read b | python myFile.py ) | read a ( read b | python myFile.py ) | read a defeats the purpose of interactive python function but this doesn't work as well. ( read b | python myFile.py ) | read a失败了交互式 python function 的目的,但这也不起作用。 It works if myfunc() is non-interactive(not expecting user input).如果myfunc()是非交互式的(不期望用户输入),它就可以工作。 The function in reality takes some input, manipulates it, and then output the result in required format. function 实际上需要一些输入,对其进行操作,然后 output 以所需格式生成结果。 I know it would be much easier to use either python or shell, but since i already wrote the python function, was wondering if it is possible to link both. I know it would be much easier to use either python or shell, but since i already wrote the python function, was wondering if it is possible to link both. If yes, is it also possible to add only final value to shell variable rather than all the print()如果是,是否也可以仅将最终值添加到 shell 变量而不是所有print()

Same issue happens(terminal gets stuck) when i do当我这样做时会发生同样的问题(终端卡住)

python myFile.py > someFilename

However file someFilename was created even though terminal was unresponsive.但是,即使终端没有响应,也会创建文件someFilename It seems shell is starting both the processes at the same time which makes sense.似乎 shell 正在同时启动这两个进程,这是有道理的。 I am guessing if somehow python myfile.py executes independently before opening the pipe it could be possible, but i may be wrong.我猜想如果python myfile.py在打开 pipe 之前独立执行,这可能是可能的,但我可能错了。

If you are working on Linux or other Unix variants, would you please try:如果您正在研究 Linux 或其他 Unix 变体,请尝试:

import os
def myfunc():
    tty = os.open("/dev/tty", os.O_WRONLY)
    os.write(tty, "enter value between 1 to 10\n")
    i=int(input())
    if(i<1 or i>10):
        os.write(tty, "again\n")
        myfunc()
    else:
        print(i)

BTW if your shell is bash , it will be better to say:顺便说一句,如果您的 shell 是bash ,最好说:

read a < <(python myFile.py)

Otherwise read a is invoked in the subshell and the variable a cannot be referred in the following codes.否则在子 shell 中调用read a并且变量a不能在以下代码中引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM