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.

if __name__ == "__main__":
instanceId = main(sys.argv)

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.

EC2_INSTANCE_ID=$(python 2>&1 >/dev/null)