Return value from Python script to bash shell

We have a legacy Python script to launch a new AWS EC2 instance. The current version of this script just lauches the instance and prints out some logs. Now we need to terminate the EC2 instance created by the script. To use the aws ec2 terminate-instances command, we need to get the instance id.

Because the script already writes some logging output to the stdout, we cannot simply use the stdout to return the instance id. An valid option is to add a verbose flag that controls when to output the logging, so we can disable the logging using command line switches. But this requires more changes to the script. So we decided to use the stderr to output the instance id. The sys.exit method can be used to output the instanceId to the stderr.

1
2
3
if __name__ == "__main__":
instanceId = main(sys.argv)
sys.exit(instanceId)

Then in the bash script, we need to ignore the stdout and capture the output of stderr. In the script below, 2>&1 means redirecting stderr to stdout, >/dev/null means ignoring the output in the original stdout, so the output will only be the content in stderr. Then we assign the output to EC2_INSTANCE_ID.

1
EC2_INSTANCE_ID=$(python ec2.py 2>&1 >/dev/null)
Comments