是否可以在终端中调用Python函数?

发布于 2025-01-24 21:39:19 字数 369 浏览 3 评论 0原文

我希望能够运行Python程序并在终端中键入A函数并使函数执行。例如:

我在Python脚本中定义了一个函数

def hi():
   print('hello')

,并且在程序运行时,我在终端中键入“ HI()”或“ HI”,并且返回“ Hello”。

我的最终目标是拥有许多可以随时称为的不同功能。我知道我可以用大量的IF/Elif语句对此进行精心编码,但这是一个混乱且看似不切实际的解决方案。

在使用中的一个示例是与Discord机器人一起使用的,可以寻找前缀并关注它并运行所谓的函数,

我可以以任何方式以清洁的方式向用户进行此操作?

#sorry用于不良格式,我对堆栈溢出非常新鲜

I want to be able to run a python program and type a function in the terminal and have the function execute. For example:

I define a function in the python script

def hi():
   print('hello')

and while program is running, I type "hi()" or "hi" in the terminal and "hello" is returned.

My end goal is to have many different functions that can be called any time. I understand I could hard-code this with a ton of if/elif statements but that is a messy and seemingly impractical solution.

An example of this in use is with discord bots that can look for a prefix and command following it and run the function that was called

Is there any way I can do this in a way that is clean looking to the user?

#sorry for bad formatting, I am pretty new to Stack Overflow

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

吹泡泡o 2025-01-31 21:39:19

这可能会变得复杂。一个基本的解决方案是从全局名称空间获取函数对象。

def hi():
    print("Hello")

def bye():
    print("Sorry, I'm staying")

while True:
    try:
        cmd = input("what up? ")
        globals()[cmd.strip()]()
    except KeyError:
        print("Invalid")

您可以使用自己的字典而不是全局名称空间,而需要初始化它。这可以帮助实施诸如帮助系统之类的东西。您甚至可以将所有命令都放在自己的模块中,使用 命名空间而不是自己的命令。

然后是提供参数的问题。如果您想做这样的事情,则可以在逗号上将字符串分开或类似的东西。

您甚至可以探索“ Python中的域特定语言”,以获取更复杂但表现力的解决方案。

This can get complicated. A basic solution is to get the function object from the global namespace.

def hi():
    print("Hello")

def bye():
    print("Sorry, I'm staying")

while True:
    try:
        cmd = input("what up? ")
        globals()[cmd.strip()]()
    except KeyError:
        print("Invalid")

You could use your own dictionary instead of the global namespace, at the cost of the need to initialize it. That can aid in implementing something like a help system. You could even put all of your commands in their own module, use its namespace instead of your own dict.

Then there is the question of supplying parameters. If you want to do something like that, you could split the string on commas, or something like that.

You could even explore "Domain Specific Languages in Python" for more complicated but expressive solutions.

萌︼了一个春 2025-01-31 21:39:19

我认为您可以使用此代码:

import sys

def hi():
   print('hello')

while True:
    c = sys.stdin.readlines(1)[0].split('\n')[0]
    eval(c)()

eval()可以将您的字符串变成函数,而sys.stdin具有读取您的CMD输入的函数。

I think you can use this code:

import sys

def hi():
   print('hello')

while True:
    c = sys.stdin.readlines(1)[0].split('\n')[0]
    eval(c)()

eval() can make your string into function and sys.stdin have function to read your cmd input.

怪我闹别瞎闹 2025-01-31 21:39:19

问题1

我希望能够运行Python程序并在
终端并执行函数。例如:

从本质上讲,您是在问:如何将可执行文件或脚本链接到命令,以便它可以在我的终端中工作。为此,首先创建您的Python脚本并将其放置在某个地方。下一步是使该脚本可以从终端内的任何目录访问。这将取决于您的平台。我首先解释Linux之后是Windows。

如果您在Linux或Mac 上,现在它的时间弄清楚了如何从任何地方而不是一个目录运行程序。

您应该在Python程序的顶部包括这两个Shebangs,以使事情易于错误。您可以用“ Python3 Shebang”和“ Python3编码Shebang”

#!/usr/bin/python3
# -*- coding: utf-8 -*-

在您的终端中开始使用“ Python3 Shebang”(Python3 Shebang)和“ Python3”(应该运行您的程序):

username@pc:~$ python3 /full/path/to/my_file.py

一旦您可以使用该工作,就该将程序链接到命令了。您可以通过在Linux/Mac上的BASH别名轻松地执行此操作,通过在主目录中的.bashrc配置文件中添加新行(在终端中使用“ CD〜”到达那里)。现在,将此行添加到您的.bashRC中以运行该示例,

alias my_command='python3 python3 /full/path/to/my_file.py'

然后使用一个别名重新启动您的终端,my_command应该从任何目录中重新启动。

如果您在Windows上,现在仍然是时候从任何地方执行文件了。首先,您必须将.py文件与解释器关联。使用“ with with with with with with”菜单,并将其文件类型分配给您的本地python.exe,

如果正确执行此操作,请双击文件应在短时间内打开终端并运行脚本,然后关闭。您可以在程序结束时添加input()调用,以使其等待Enter关闭。

现在是时候将/full/path/to/my_file.py.py.py添加到Windows System PATH,以便它可以从终端中的任何文件夹中使用。您可以通过在系统路径中添加新文件夹来做到这一点。在这种情况下,这意味着将/fult/path/to/添加到路径。另外,您可以将脚本放在已经在路径中的某个地方,例如c:\ Windows \ System32c:\ windows \

现在,重新启动您的终端,使用my_file应该运行脚本。如果您希望将脚本放置在自定义位置而不是已经进入路径中的文件夹,请参见如何将文件夹添加到Windows 10中的路径环境变量(带屏幕截图)



问题2

并且在程序运行时,我在终端中键入“ hi()”或“ hi”,返回“ hello”。

我认为您的意思是打印而不是在这种情况下返回。很难将字符串返回到控制台。您正在寻找输入函数以在此处获取用户输入。



问题3

我的最终目标是拥有许多不同的功能,可以随时调用。我知道我可以用大量的if/elif语句对此进行硬编码,但这是一个混乱且看似不切实际的解决方案。

您可以为此制作多个小程序,也可以制作一个大型程序。您还应该搜索没有喜欢的搜索引擎的“ Python命令行参数”。学习这对任务很有用。



问题4

使用的一个示例是与Discord机器人一起使用,可以查找前缀并关注它并运行称为

的函数

完全不同的问题。您应该搜索有关与Python不满机器人的信息。使命令在不和谐中起作用与使其在您的控制台中工作有很大不同。

问题5

有什么办法可以以一种清洁的方式来对用户进行干净?

是的。您应该查看python的input()函数,并可能弄清楚如何清除终端屏幕,例如:

import os

def clear():
    cmd = "clear" # default to linux command
    if os.name == ("nt"):  # If Machine is running on Windows, use cls
        cmd = "cls"
    os.system(command)

>>> clear()

使“清洁”中的“清洁”完全不同,您必须首先在Discord上了解更多信息机器人。我建议YouTube教程和Discord的正式文档。

Question 1

I want to be able to run a python program and type a function in the
terminal and have the function execute. For example:

In essence you are asking: how can I link an executable or script to a command so that it will work in my terminal. To do that, first create your Python script and place it somewhere. Next step is making the script accessible from any directory within a terminal. This will depend on your platform. I explain linux first followed by windows.

If you are on linux or mac, now its time figure out how to run the program from anywhere instead of one directory.

You should include these two shebangs at the top of your Python program to make things less error-prone. You can google their meaning with "python3 shebang" and "python3 encoding shebang"

#!/usr/bin/python3
# -*- coding: utf-8 -*-

Start with this in your terminal (it should run your program):

username@pc:~$ python3 /full/path/to/my_file.py

Once you get that working, it's time to link your program to a command. You can do that easily with a bash alias on linux/mac by adding a new line to your .bashrc configuration file which is located in your home directory (use "cd ~" in terminal to get there). Now add this line to your .bashrc to run the example with an alias

alias my_command='python3 python3 /full/path/to/my_file.py'

Now restart your terminal and my_command should from any directory.

If you are on windows, now its still time to make the file executable from anywhere. First you have to associate .py files with the interpreter. use the "open with" menu and assign it file type to your local python.exe

If you did this correctly, double clicking the file should open the terminal for a brief moment and run the script and then close. You can add input() call at the end of your program to leave it waiting for enter to close.

Now its time to add /full/path/to/my_file.py to windows system PATH so that it can work from any folder in the terminal. You can do this by adding a new folder to your system PATH. In this case it would mean adding /full/path/to/ to the PATH. Alternatively you can place the script somewhere that is already in the PATH like C:\WINDOWS\system32 or C:\WINDOWS\.

Now restart your terminal, and using my_file should run your script. If you wish to place the script in custom location instead of folders already in PATH, see How to add a folder to `Path` environment variable in Windows 10 (with screenshots)



Question 2

and while program is running, I type "hi()" or "hi" in the terminal and "hello" is returned.

I assume you mean printing instead of returning in this context. It would be hard to return string to the console. You are looking for the input function to take user input here.



Question 3

My end goal is to have many different functions that can be called any time. I understand I could hard-code this with a ton of if/elif statements but that is a messy and seemingly impractical solution.

You can make multiple small programs for this, or one large program. You should also search for "python command line arguments" without favorite search engine. Learning this will be useful for the task.



Question 4

An example of this in use is with discord bots that can look for a prefix and command following it and run the function that was called

This is entirely different question. You should search for information on making discord bots with python. Making commands work in discord is very different than making them work in your console.

Question 5

Is there any way I can do this in a way that is clean looking to the user?

Yes. You should look into input() function of python and possible figuring out how to clear the terminal screen such as:

import os

def clear():
    cmd = "clear" # default to linux command
    if os.name == ("nt"):  # If Machine is running on Windows, use cls
        cmd = "cls"
    os.system(command)

>>> clear()

Making things "clean" in discord is entirely different question and you have to first learn more on Discord bots. I suggest youtube tutorials and the official documentation from discord.

病女 2025-01-31 21:39:19

您可以在终端中使用易于终端

from easy_terminal import terminal

@terminal()
def hi():
    print("Hello!")


@terminal()
def hello(answer: str = "world"):
    print(f"Hello {answer}!")

类型HI或Hello来查看结果

you can use easy-terminal

from easy_terminal import terminal

@terminal()
def hi():
    print("Hello!")


@terminal()
def hello(answer: str = "world"):
    print(f"Hello {answer}!")

type hi or hello in the terminal to see the result

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文