简体   繁体   中英

Return value from shell script to python script

I am trying to achive following:

  1. I am having a python script which is calling a shell script and passing a parameter as well. Shell script creates a tar.gz file using that parameter passed in some location.

  2. Now shell script should pass the name and location of the tar.gz so created. Python script uses that to form a JSON and pass to some other code.

  3. Along with this I want to add some check to make sure if tar.gz is generated then only value is returned to python otherwise not.

Here is the code:

Python script:

#!/usr/bin/python

import json
import subprocess

json_data='{"name": "StackOverflow", "uid": "8fa36334-ce51"}'

data = json.loads(json_data)
for keys,values in data.items():
  print(keys)
  print(values)

 UID = data.get('uid')

 rc = subprocess.check_output(["/home/cyc/Cyc-    
        Repo/cyc_core/cyc_platform/src/package/cyc_bsc/scripts/test.sh",    
        UID])
 print rc
 if rc != 0:
   print "failed for passed in uid"

data_op = {}
data_op['pathTOCompressfile'] = 'value_should_be_return_from_shell'
data_op['status'] = 'OK'
json_data_op = json.dumps(data_op)

print json_data_op

shell script:

#!/bin/bash

if [ "$1" != "" ]; then
   uid=$1
   echo "Positional parameter 1 contains something $1"
else
   echo "Positional parameter 1 is empty"
fi

LOG_TMP="tmp_log_file_location"

log_location="log_file_location"

filename="${log_location}/$uid.tar.gz"
echo $filename
tar -zcvf $filename -C $LOG_TMP/dc .

This is what i am not able to understand:

  1. How to pass back the value of variable "filename" back to python script if tar -zcvf command is successful.
  2. In python script how can i verify take value of filename and create JSON using that
  3. In case value cannot be generated STATUS becomes fail in JSON ( within python ) so capture that as well.

Your shell script writes the name of the generated file to standard output, so your question boils down to how to catch stdandard output of a subprocess started from Python. This has been ansered here . BTW, when asking questions about Python, it would be a good idea to always specify the Python version you are using.

In your case however, I would redesign your shell script a bit:

Your script outputs not only the generated filename, but also messages about the "positional parameter", and this means that you would have to fiddle them apart in your script, whether it is an message or a valid output. You could send the messages to standard error, to keep them apart.

BTW, if there is no positional parameter, the generated file name is just .tar.gz . Is this really what you want to have? Wouldn't it better to do a exit 1 , if there is no parameter?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM