Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a python function as a bash command

Tags:

python

bash

shell

There is a lot of literature on how to run shell commands from python, but I am interested in doing the opposite. I have a python module mycommands.py which contains functions like below

def command(arg1, arg2):
    pass

def command1(arg1, arg2, arg3):
    pass

where the function arguments are all strings. The objective is to be able to run these functions from bash like below

$ command arg1 arg2 
$ command1 arg1 arg2 arg3 

So far I have the following brute setup in .bash_profile where I have to provide bash bindings to each python function manually

function command() {
    python -c "import mycommand as m; out=m.command('$1', '$2'); print(out)"
}

function command1() {
    python -c "import mycommand as m; out=m.command1('$1', '$2', '$3'); print(out)"
}

It would be nice if one could have a single bash command like

$ import_python mycommands.py

which would automatically import all the python functions in the module as bash commands. Does there exist a library which implements such a command?

like image 632
D R Avatar asked Apr 19 '15 18:04

D R


People also ask

How do you call a Python function in bash?

4 Answers. Show activity on this post. python -c'import themodule; themodule. thefunction("boo!")'

Can you run a Python script in a bash script?

Generally, a Python script will have the file extension PY. However, there's another way of writing a Python script: embedding Python codes into a bash script. Either way, you need to have the Python package installed in your system.

How do I run a Python function in terminal?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

Can you write functions in bash?

Bash provides some built-in functions such as echo and read , but we can also create our own functions.


1 Answers

You can create a base script, let's say command.py and check with what name this script was called (don't forget to make it executable):

#!/usr/bin/python
import os.path
import sys

def command1(*args):
    print 'Command1'
    print args

def command2(*args):
    print 'Command2'
    print args


commands = {
    'command1': command1,
    'command2': command2
}

if __name__ == '__main__':
    command = os.path.basename(sys.argv[0])
    if command in commands:
        commands[command](*sys.argv[1:])

Then you can create soft links to this script:

ln -s command.py command1
ln -s command.py command2

and finally test it:

$ ./command1 hello
Command1
('hello',)

$ ./command2 world
Command2
('world',)
like image 169
JuniorCompressor Avatar answered Oct 25 '22 17:10

JuniorCompressor