0

I'm trying to implement a command which involves sending POST/GET request to a remote server and interpret JSON format result. Since it's quite hard to parse JSON via bash, I decide to write python script first and call it within the shell script.

My shell script now looks like this

#!/bin/sh
case $1 in
  submit-job)
    python3 src/submit-job.py
    ;;
  lists-job)
    python3 src/lists-job.py
    ;;
  ....and so on
esac

I hope my users can use this command as following.

Job submit-job argument1 argument2...
Job lists-job
...and so on

Basically. I have only 1 Python class file called Job.py including multiple functions like submit-job and lists-job. However, in order to separate different functions to a different command argument, I have to create seperate python files to trigger it. (Like submit-job.py and lists-job.py).

For example. submit-job.py

from Job import Job

j = Job()
j.submit_job()

lists-job.py

from Job import Job

j = Job()
j.lists_job()

As you can see, they are quite similar. Is there a better way or best practice to achieve what I want?

rj487
  • 4,476
  • 6
  • 47
  • 88
  • 1
    `python job-tools.py submit`, and then have your Python script check its command-line arguments. (Even better, have distutils/setuptools create an executable wrapper, then it's just `job-tools submit`, no needing to explicitly call the python interpreter). – Charles Duffy Jun 17 '19 at 20:50
  • A common technique is to have a single file with multiple links, and then have the program examine $0. – William Pursell Jun 17 '19 at 20:50
  • @WilliamPursell, ...or, in the Python sense, examine `sys.argv[0]`. – Charles Duffy Jun 17 '19 at 20:50
  • Thanks! I will take a look on distutils – rj487 Jun 18 '19 at 19:57

1 Answers1

0

Why don't you do the if/else in Python?

import sys
from Job import Job

j = Job()
arg = sys.argv[1]
if arg == 'submit-job':
    j.submit_job()
elif ...
    ...

Now you can call this from within the bash script, passing the argument, or even remove the bash script already and invoke the Python script directly from the command line.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895