Ich habe diesen Code:
def hello():
return 'Hi :)'
Wie kann ich dies direkt von der Befehlszeile aus ausführen?
Ich habe diesen Code:
def hello():
return 'Hi :)'
Wie kann ich dies direkt von der Befehlszeile aus ausführen?
Dieses Skript ähnelt den anderen Antworten hier, aber es listet auch die verfügbaren Funktionen mit Argumenten und Dokumentationen auf:
"""Small script to allow functions to be called from the command line.
Run this script without argument to list the available functions:
$ python many_functions.py
Available functions in many_functions.py:
python many_functions.py a : Do some stuff
python many_functions.py b : Do another stuff
python many_functions.py c x y : Calculate x + y
python many_functions.py d : ?
Run this script with arguments to try to call the corresponding function:
$ python many_functions.py a
Function a
$ python many_functions.py c 3 5
3 + 5 = 8
$ python many_functions.py z
Function z not found
"""
import sys
import inspect
#######################################################################
# Your functions here #
#######################################################################
def a():
"""Do some stuff"""
print("Function a")
def b():
"""Do another stuff"""
a()
print("Function b")
def c(x, y):
"""Calculate x + y"""
print(f"{x} + {y} = {int(x) + int(y)}")
def d():
# No doc
print("Function d")
#######################################################################
# Some logic to find and display available functions #
#######################################################################
def _get_local_functions():
local_functions = {}
for name, obj in inspect.getmembers(sys.modules[__name__]):
if inspect.isfunction(obj) and not name.startswith('_') and obj.__module__ == __name__:
local_functions[name] = obj
return local_functions
def _list_functions(script_name):
print(f"Available functions in {script_name}:")
for name, f in _get_local_functions().items():
print()
arguments = inspect.signature(f).parameters
print(f"python {script_name} {name} {' '.join(arguments)} : {f.__doc__ or '?'}")
if __name__ == '__main__':
script_name, *args = sys.argv
if args:
functions = _get_local_functions()
function_name = args.pop(0)
if function_name in functions:
function = functions[function_name]
function(*args)
else:
print(f"Function {function_name} not found")
_list_functions(script_name)
else:
_list_functions(script_name)
Führen Sie dieses Skript ohne Argument aus, um die verfügbaren Funktionen aufzulisten:
$ python many_functions.py
Available functions in many_functions.py:
python many_functions.py a : Do some stuff
python many_functions.py b : Do another stuff
python many_functions.py c x y : Calculate x + y
python many_functions.py d : ?
Führen Sie dieses Skript mit Argumenten aus, um zu versuchen, die entsprechende Funktion aufzurufen:
$ python many_functions.py a
Function a
$ python many_functions.py c 3 5
3 + 5 = 8
$ python many_functions.py z
Function z not found
Etwa so: call_from_terminal.py
# call_from_terminal.py
# Ex to run from terminal
# ip='"hi"'
# python -c "import call_from_terminal as cft; cft.test_term_fun(${ip})"
# or
# fun_name='call_from_terminal'
# python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
def test_term_fun(ip):
print ip
Dies funktioniert in der Bash.
$ ip='"hi"' ; fun_name='call_from_terminal'
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi
Nachfolgend finden Sie die Datei Odd_Even_function.py, die die Definition der Funktion enthält.
def OE(n):
for a in range(n):
if a % 2 == 0:
print(a)
else:
print(a, "ODD")
Um nun das Gleiche von der Eingabeaufforderung aus aufzurufen, habe ich die folgenden Optionen gewählt.
Optionen 1 Vollständiger Pfad der Exe-Datei \python.exe -c "import Ungerade_Gerade_Funktion; Ungerade_Gerade_Funktion.OE(100)"
Option 2 Vollständiger Pfad der Exe-Datei \python.exe -c "from Odd_Even_function import OE; OE(100)"
Danke.
Es ist immer möglich, python in der Kommandozeile mit dem Befehl python
dann importieren Sie Ihre Datei so importiere beispiel_datei
dann führen Sie den Befehl mit beispiel_datei.hallo()
Dadurch wird die seltsame .pyc-Kopierfunktion vermieden, die jedes Mal auftaucht, wenn Sie python -c usw. ausführen.
Vielleicht nicht so bequem wie ein Einzelbefehl, aber eine gute schnelle Lösung, um eine Datei von der Kommandozeile aus zu texten, und ermöglicht es Ihnen, Python zum Aufrufen und Ausführen Ihrer Datei zu verwenden.
CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.