[英]How do you make a discord bot respond without commands (but in python)?
[英]How do you make a console application which accepts commands?
我對Python和一般編程還比較陌生。 我正在編寫控制台應用程序。
如何編寫一個在終端中接受命令的控制台應用程序? 例如,就像終端本身如何接受命令並執行相應任務一樣。 “命令”實際上只是用戶調用的應用程序中的功能嗎? 控制台界面本身就是功能嗎? 例如:
def console_interface():
user_input = input()
if user_input == "some_function":
some_function()
if user_input == "some_other_function":
some_other_function()
盡管效率不高,但我知道上面的方法是因為我已經對其進行了測試。 這個一般想法是正確的還是遙遙無期?
Python的標准庫提供了一個模塊,該模塊完全封裝了“接受命令的控制台應用程序”功能:請參閱https://docs.python.org/3/library/cmd.html 。
在該模塊中,命令實際上是您的類的方法 ,根據命名約定, do_that
cmd.Cmd
: do_this
, do_that
等子類cmd.Cmd
。 https://docs.python.org/3/library/cmd.html#cmd-example上的示例是烏龜圖形的豐富“控制台接受命令”,因此您可以使用它。
從理論上講,您可能想從http://pymotw.com/2/cmd/上給出的簡單得多的示例開始-就是Python 2,但是功能幾乎相同。 一系列優秀的示例需要一些改動才能在Python 3中運行,但是它並不難。
例如,考慮第一個:
import cmd
class HelloWorld(cmd.Cmd):
"""Simple command processor example."""
def do_greet(self, line):
print "hello"
def do_EOF(self, line):
return True
if __name__ == '__main__':
HelloWorld().cmdloop()
當用戶終止標准輸入(在Unix上為control-D)時,將發生do_EOF
。 如https://docs.python.org/3/library/cmd.html#cmd.Cmd.cmdloop所說,
An end-of-file on input is passed back as the string 'EOF'.
(在這種情況下, return True
終止程序)。
您只需更改即可在Python 2(而不是3)中運行它,那就是一行:
print "hello"
必須成為
print("hello")
因為print
是Python 2中的一條語句,現在已成為Python 3中的函數。
我發現http://www.opensource.apple.com/source/python/python-3/python/Lib/cmd.py上的cmd.py
資料也很有啟發性,我建議您對它們進行研究,作為對的介紹。 “調度”的世界...!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.