Is it possible to call a python function in a terminal?

Question:

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

Asked By: Emerson Meadows

||

Answers:

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.

Answered By: tdelaney

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.

Answered By: PinkR1ver

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:WINDOWSsystem32 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.

Answered By: Markus Hirsimäki

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

Answered By: Phnx