8

In the following code, I construct a variable $probe1 that I want to then pass to a bash script. I the toy example below, the output is blank, i.e. $probe1 is not recognized the the bash shell script within the os.system call. What needs to be done?

for line1 in datfile:
    datmat=datmat+[line1.rstrip('\n').split('\t')]
        probe=datmat[i][0]
        snp1=datmat[i][2]
    probe1='permprobes'+probe+'pheno.pphe'
    os.system('echo $probe1')
5
  • probe1 = '...' sets a Python variable. It has no connection to Bash whatsoever. Commented Dec 19, 2012 at 1:09
  • Is there some way to carry over a variable from python to the bash shell? That's essentially my question. Commented Dec 19, 2012 at 1:14
  • Why would you need to do this? Commented Dec 19, 2012 at 1:15
  • I'm using python to extract some variable names, which I then need to pass as arguments to a program that's executed from a bash script. Therefore, I need to export the string $probe1 to a bash shell (I'm just using echo as a simple example to illustrate the problem) Commented Dec 19, 2012 at 1:22
  • But why do you need the variables? Why don't you just quote the arguments and pass them directly to the script? Commented Dec 19, 2012 at 1:23

2 Answers 2

10

Seems like this is what you are trying to do:

In [2]: os.environ['probe1'] = 'hello'

In [3]: os.system('echo $probe1')
hello

But I have no idea why you would like to do this ...

Sign up to request clarification or add additional context in comments.

3 Comments

I'm using python to extract some variable names from a data file, which I then need to pass to a bash shell script to run in another program. The example with echo is just a "toy" script to illustrate the problem of moving a variable from python into a bash shell.
@user1815498 Maybe you can use a pipe to do that: docs.python.org/2/library/subprocess.html
In any case, the os.environ[ ] solution you propose solves my problem. Thank you for the pipe reference, it will come in handy when I need to pass multiple variables from python to the shell.
4
os.system('echo {0}'.format(probe1))

probe1 is a python variable, not a shell variable.

os.environ['probe1'] = probe1

will set the bash environment variable to the python variable contents. Once the python script exits though, the environment variable goes away.

1 Comment

I know that, my question is how I can transfer a python variable to the bash shell.

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.