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
2
  • What's in script.sh? Commented Aug 7, 2021 at 6:33
  • @bereal, edited question Commented Aug 7, 2021 at 6:41

1 Answer 1

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.

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

5 Comments

You really want to avoid the unnecessary shell=True here, too. See also Actual meaning of shell=True in subprocess
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 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.
@tripleee although if I remove the shell=True, I'm getting FileNotFoundError. Any idea why?
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)], ...)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.