簡體   English   中英

Output 的交互式 python 到 shell 變量

[英]Output of interactive python to shell variable

有一個交互式 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)

我想將最終的 output print(i)存儲在 shell 變量中。 就像是

python myFile.py | read a

每次我運行命令時,上面的查詢都會卡住。 有可能這樣做嗎? 即使( read b | python myFile.py ) | read a ( read b | python myFile.py ) | read a失敗了交互式 python function 的目的,但這也不起作用。 如果myfunc()是非交互式的(不期望用戶輸入),它就可以工作。 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. 如果是,是否也可以僅將最終值添加到 shell 變量而不是所有print()

當我這樣做時會發生同樣的問題(終端卡住)

python myFile.py > someFilename

但是,即使終端沒有響應,也會創建文件someFilename 似乎 shell 正在同時啟動這兩個進程,這是有道理的。 我猜想如果python myfile.py在打開 pipe 之前獨立執行,這可能是可能的,但我可能錯了。

如果您正在研究 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)

順便說一句,如果您的 shell 是bash ,最好說:

read a < <(python myFile.py)

否則在子 shell 中調用read a並且變量a不能在以下代碼中引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM