簡體   English   中英

如何讓 Python 程序從終端連續運行(直到我手動停止它)?

[英]How can I make a Python program run continuously from the Terminal (until I stop it manually)?

我有一個 python 程序,它從用戶那里獲取輸入(單個字符,'y' 或 'n'),然后根據該輸入執行某個任務。 我的需要是允許這個程序從終端連續運行,直到我決定停止它。 目前,我必須繼續返回終端並從那里執行程序(並始終輸入該單個字符)。

PS:如果有幫助:該程序將數據添加到MySQL數據庫,所以我需要它以使整個過程自動化(從而更快一點)

編輯

我的my-program.py看起來像這樣:

main():
    if input().lower()=='y':
        #does something here
    else:
        #does something else

我的要求是從終端無限地運行 Python 程序。 我知道如何使用循環以及如何根據用戶輸入執行任務。 我想要的是在出現提示時自動將 'n' 作為輸入字符輸入。

my-program.py在輸入字符時執行特定操作。 當我使用如下所示的 while 循環從另一個 Python 程序調用my-program.main()時,我想在出現提示時繼續傳遞相同的輸入(比如'n' )(當my-program.pyinput()語句被執行)

import my-program
while True:
    my-program.main()

首先安裝鍵盤包:

pip3 install keyboard

然后編寫代碼:

import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
        else:
            pass
    except:
        break  # if user pressed a key other than the given key the loop will break

來源: 鍵盤輸入檢測

一般情況:'yes' 命令,它會使用 'y' 作為您的默認選項,並且不會一遍又一遍地詢問您。

$man 是的

是 - 重復輸出一個字符串直到被殺死 [...]

描述:重復輸出包含所有指定 STRING(s) 或 'y' 的行。 它可能相當於 --force-yes ,因此很危險。 如果你仍然想這樣做,你可以通過管道輸出 yes:

yes | <command>

暫無
暫無

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

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