0

I'm trying to pass variables from python script to bash, but not able to invoke the variable in bash.

clustername=sys.argv[1]

subprocess.check_call("/data/path/script.sh '%s'" % str(clustername), shell=True, stdout=subprocess.PIPE, universal_newlines=True)

And tried to print subprocess output, but was not able to print. It is returning only code

Below is the bash script:

#!/bin/bash
clustername=$clustername # invoking from pythonscript
------
---Some logic -
---end
mtm
  • 504
  • 1
  • 7
  • 25
kiran k
  • 41
  • 8

1 Answers1

2

Firstly, in the bash file you are supposed to do:

#!/bin/bash
clustername=$1 # invoking from pythonscript

to get the command line arguments passed into the script.

Secondly, using check_call(), you will not be able to catch the output from the bash script. You will need to use subprocess.run() or subprocess.check_output() or something similar to achieve that.

You can try doing the following:

import sys
import subprocess

clustername=sys.argv[1]
print(subprocess.run(["/data/path/script.sh", str(clustername)], universal_newlines=True).stdout)

check_call() will only return the return code and not the stdout. You can also try check_output() if you want to see the output.

You can also do the following using check_output:


print(subprocess.check_output(["/data/path/script.sh", str(clustername)], universal_newlines=True))
Edit

Removed shell=True as suggested in the comments.

mtm
  • 504
  • 1
  • 7
  • 25
  • 2
    You really want to avoid the unnecessary `shell=True` here, too. See also [Actual meaning of `shell=True` in `subprocess`](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess) – tripleee Aug 07 '21 at 07:17
  • 1
    If you only want to display the output to the user, capturing it so you can then print it is just inefficient. If you don't pass a `stdout=` keyword argument, the default behavior is for the subprocess to print directly to standard output, outside of Python's view or control. – tripleee Aug 07 '21 at 07:20
  • @tripleee thanks for the input. I will update the answer to reflect these changes. I'm not very thorough with Python and hence bound to write inefficient code. – mtm Aug 07 '21 at 07:30
  • @tripleee although if I remove the `shell=True`, I'm getting `FileNotFoundError`. Any idea why? – mtm Aug 07 '21 at 07:37
  • 2
    Like the linked question's answers reveal, you need to refactor to pass a list if you omit `shell=True`, i.e. `subprocess.run(["/data/path/script.sh", str(clustername)], ...)` – tripleee Aug 07 '21 at 07:40