3

I have written a library in python, that is kind of like a scripting language, and I had the idea of turning the library into a terminal executable that could be called like:

myprogram /path/to/file

So like python runs .py, this would run the file with the functions defined in my library. Is this at all possible?

7
  • 2
    Put #!/usr/bin/python as first line. THen chmod +x myprogram.py Commented Oct 15, 2015 at 1:01
  • that in no way answers the question. How can i make a program that runs the .whatever file with the defined function. Similar to a library but from the command line. Commented Oct 15, 2015 at 1:02
  • Aha! Sorry, misunderstood the question. So you need a dispatcher. YOu could make executable.py as I said and then make links to that in the form of libfun1, lbfun2, ... In the executable.py you make check over what is the zeroeth sys.argv, and based upon sys.argv[0] you dispatch to particular function Commented Oct 15, 2015 at 1:07
  • so basically a command line app that reads the file, and for each matching function in the file, runs that particular function? Commented Oct 15, 2015 at 1:10
  • @tristan no, he wants something like busybox as far as I understand Commented Oct 15, 2015 at 1:10

1 Answer 1

0

Suppose you write function like this

#!/usr/bin/python

import sys

if (sys.argv[0] == "./funA.py"):
    print("Calling A")
    # ...
    sys.exit(0)

if (sys.argv[0] == "./funB.py"):
    print("Calling B")
    # ...
    sys.exit(0)

print(sys.argv[0])

YOu call it main.py. Then you make links like this

$ `ln main.py funA.py`
$ `ln main.py funB.py`

It is really just one code, with three names and link count is equal to 3. But if you run it

./funA.py

it will be dispatched to funA block in your code. But if you run it

./funB.py

it will be dispatched to funB block in your code. And so on and so forth

Is it what you're looking for?

Sign up to request clarification or add additional context in comments.

2 Comments

yeah thats perfect!! thanks!
Glad to hear. This is how busybox for small systems works. It is all small unix functions utils like ln, ls, cat etc together. One executable linked statically, but then tons of links set from it to look like ln, ls, cat. And pretty much same dispatcher logic is selecting what function to run inside