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?

  • 2
    Put `#!/usr/bin/python` as first line. THen `chmod +x myprogram.py` – Severin Pappadeux Oct 15 '15 at 01: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. –  Oct 15 '15 at 01: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 – Severin Pappadeux Oct 15 '15 at 01:07
  • so basically a command line app that reads the file, and for each matching function in the file, runs that particular function? –  Oct 15 '15 at 01:10
  • @tristan no, he wants something like `busybox` as far as I understand – Severin Pappadeux Oct 15 '15 at 01:10
  • No, it is still unclear what you want, so let me write short answer and see if it is what you want – Severin Pappadeux Oct 15 '15 at 01:12
  • ok, yeah maybe i didnt ask the question the best.. –  Oct 15 '15 at 01:13

1 Answers1

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?

Severin Pappadeux
  • 15,291
  • 3
  • 27
  • 51
  • yeah thats perfect!! thanks! –  Oct 15 '15 at 01:23
  • 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 – Severin Pappadeux Oct 15 '15 at 01:28