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?

4
  • 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). Commented Jun 17, 2019 at 20:50
  • A common technique is to have a single file with multiple links, and then have the program examine $0. Commented Jun 17, 2019 at 20:50
  • @WilliamPursell, ...or, in the Python sense, examine sys.argv[0]. Commented Jun 17, 2019 at 20:50
  • Thanks! I will take a look on distutils Commented Jun 18, 2019 at 19:57

1 Answer 1

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.

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

1 Comment

This is a good approach I have not thought about it. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.