0

I have two files at the same location.

The first file is sh file and other is python file.

a.sh file

#!/bin/bash
a=1
b=1
if [[ $a -eq $b ]]
then
   call the python file function named callable with command line argument as value of a
   # python b.py $a
fi

b.py file

This file has many functions but I need to call specifically function callable:

arg = sys.argv[1]

def callable():
   print(arg)

How can I do that in script?

Avenger
  • 793
  • 11
  • 31
  • Combining shell and python scripts is always ugly, but if you have to do so, you should take a look at python's argparse module. – DocDriven Dec 14 '20 at 10:03
  • @EatPayBong: What is a _file function_ supposed to be? It would help if you would write concrete input for your program and concrete output. As it currently stands, I don't know what you want to achieve. – user1934428 Dec 14 '20 at 11:39
  • You need to consider your Python script as a CLI and use argparse (or equivalent) for that. Then you will need to implement the routing to your callable. – MetallimaX Dec 14 '20 at 12:43

2 Answers2

0

add this at the bottom of your python script:

if __name__ == '__main__':
    globals()[sys.argv[1]]()

then in the bash script call the function you want

python b.py callable
# or
python b.py $a
d-xa
  • 514
  • 2
  • 7
0

Are you simply looking for this?

if __name__ == '__main__':
    callable()

By the by, you want to fix the quoting in your shell script.

#!/bin/bash
a=1
b=1
[[ "$a" -eq "$b" ]] && python b.py "$a"

See also When to wrap quotes around a shell variable.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Initially I was thinking about providing this solution as well, but guessed maybe he/she wants to also call other functions from b.py – d-xa Dec 14 '20 at 11:57