1

When I run this two commands in Ubuntu terminal I get a variable value

1. source script.sh

2. echo $varname

Where scripts.sh contains the variable being defined which is than called with echo in step 2.

How do I accomplish the same in python script: I have tried the following code

#!/bin/bash

import subprocess

command=['bash','-c','source ia_servers']
cmdout = subprocess.Popen(command, stdout=subprocess.PIPE)

filtercommand=['bash','-c','echo $IA_SRV_cs68_64']
filtered = subprocess.Popen(filtercommand, stdin=cmdout.stdout, stdout=subprocess.PIPE)

output, err = filtered.communicate()

print(output)

Description: I first ran step 1 using subprocess and the result of it fed as input to the step 2. I know there wont come any output in the first steps. But how do I accomplish this in python.

Or am I following the wrong way. If there is another way to solve this problem

Primary Goal:

my purpose is to get the variable value being set in the bash scripts to my python codes.

2
  • 1
    Why have you got a bin/bash shebang at the top of a python script? Also you can't source a python script from bash since they are different languages. Commented Jun 7, 2017 at 12:01
  • 1
    You could use os.getenv()? Commented Jun 7, 2017 at 12:04

1 Answer 1

2

Every subprocess call spawns its own instance of shell. So, any shell variable set in source in first subprocess is lost immediately when the shell exits. The only way to get an access to those variables is to print them immediately from the same subprocess call, when source is called:

import subprocess

filtercommand=['bash','-c','source ia_servers; echo $IA_SRV_cs68_64']
filtered = subprocess.Popen(filtercommand, stdout=subprocess.PIPE)

output, err = filtered.communicate()

print(output)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks alot, Actually I use to do the two steps way for the pipes command so tried similar way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.