0

I have an existing python script with command params that outputs a string like below . I am trying to call this into another python script and pass the prodName dynamically through another variable.

I tried something like this which works:

#!/usr/bin/env python
import subprocess

subprocess.call("/usr/st/getProdID.py ProdName=someProd_name Prod_config=/usr/st/prod/prod_id.txt", shell=True)

output:

Ad897

I could not redirect this output to a variable

#!/usr/bin/env python
import subprocess

pid = subprocess.call("/usr/st/getProdID.py ProdName=someProd_name Prod_config=/usr/st/prod/prod_id.txt", shell=True)
print "pid = ", pid

output:

Ad897

Pid = 0

Any help is appreciated. Thankyou!

sp77
  • 35
  • 3
  • 2
    As an aside, python 2.x is end-of-life. Consider using python 3. The answer is a bit different between 2.x and 3.x. – tdelaney Oct 08 '21 at 18:38
  • 1
    Why dont you just `import` getProdID and use it? – balderman Oct 08 '21 at 18:40
  • `check_output` and `Popen` followed by `communicate` are the two most common ways of capturing output. There are examples in the subprocess documentation. – tdelaney Oct 08 '21 at 18:45

1 Answers1

1

With Python3 you could run:

p = subprocess.run(["getProdID.py", f"ProdName={prod}", "Prod_config=/usr/st/prod/prod_id.txt"], capture_output=True)
output = p.stdout

On Python2 things are litter trickier:

p = subprocess.Popen(["getProdID.py", "ProdName={0}".format(prod), "Prod_config=/usr/st/prod/prod_id.txt"], stdout=subprocess.PIPE)
output = p.stdout.read()
noamcohen97
  • 453
  • 3
  • 13
  • You may need to decode that p.stdout. I don't think you need a note about importing. There are many reasons to call instead of import - number 1, its written as a script that takes arguments and is not in your PYTHONPATH so likely isn't an importable module at all. Calling scripts and parsing output is a normal design. – tdelaney Oct 08 '21 at 18:43
  • @thecohenman i tried this but it says >TypeError: __init__() got an unexpected keyword argument 'capture_output' however i tried this and this works better: `p = subprocess.check_output(["getProdID.py", f"ProdName={prod}", "Prod_config=/usr/st/prod/prod_id.txt"])` `print ("pid =", p)` > pid = b'Ad897\n' – sp77 Oct 08 '21 at 18:54
  • maybe you are using python2. edited the answer – noamcohen97 Oct 08 '21 at 19:01
  • actually, subprocess.check_output, calls subprocess.Popen(stdout=PIPE) – noamcohen97 Oct 08 '21 at 19:06