0

The question is related to Linux Debian, bash and python3.

Run python3 file from bash, send parameter from bash to py and output the result by echo on bash.

The follow are a sample which works for me. This one start a python3 script by bash and get the outpup of python3 script on terminal.

bash_script.sh

#!/bin/bash
python3 python_script.py

python_script.py #!/usr/bin/env python3

 import random # import the random module
  
# determining the values of the parameters 
mu = 100
sigma = 25
  
print(random.normalvariate(mu, sigma))

Whats my question: How to change the code, for send the parameter for "mu" and "sigma" from bash to python and output the python result on bash by "echo $python_script_output" ?

Follow the not working draft for a solution:

bash_script.sh

#!/bin/bash
mu = 100
sigma = 25
python3 python_script.py
echo $python_script_output

python_script.py

#!/usr/bin/env python3 
import random           
print(random.normalvariate(mu, sigma))
Biffen
  • 6,249
  • 6
  • 28
  • 36
  • 1
    **1** `mu = 100` does not assign `100` to `$mu`. That’d be `mu=100`. **2** Python will have no idea about Bash’s variables. Either `export` them os pass them as arguments. – Biffen Jan 13 '21 at 15:06
  • 2
    This smells a bit like an [XY problem](http://mywiki.wooledge.org/XyProblem). _Why_ do you need to use Bash _and_ Python? Either one could probably do whatever it is you want to do (but one might be better at it). Using both seems like asking for trouble. – Biffen Jan 13 '21 at 15:08
  • @Biffen, I need this sample to solve a lot of equal related by self after than. I only need a solution wich works on this way, no shorter solution on other way. –  Jan 13 '21 at 15:23

1 Answers1

0

Is there a particular reason you are looking to run the python script via bash?

If not, you can use in-built python module sys to pass arguments to the python script and print results directly on terminal.

import sys

def func(arg1, arg2):
    # do_somehing
arg1, arg2 = sys.argv[1], sys.argv[2]
print(func(arg1, arg2))

Then you can use it directly from bash

python script_name.py arg1 arg1
tripleee
  • 175,061
  • 34
  • 275
  • 318
lllrnr101
  • 2,288
  • 2
  • 4
  • 15
  • 1
    This is already discussed in answers to [How to pass a bash variable to Python?](https://stackoverflow.com/questions/7521061/how-to-pass-a-bash-variable-to-python). See the *Answer Well-Asked Questions* section of [How to Answer](https://stackoverflow.com/help/how-to-answer), and particularly the bullet point regarding questions that "have been asked and answered many times before". – Charles Duffy Jan 13 '21 at 15:24
  • @lllrnr101 how to use your solution for my asked script ? –  Jan 13 '21 at 15:31