Eradzh Rakhmatov
Eradzh Rakhmatov

Reputation: 9

Cannot access shell variable from python script

I am using OSX terminal and Python 2.7

My shell script:

#!/bin/bash
echo Enter the name of the file
read fileName
python gulp.py  

My python script:

import os                       #import vars
try:
    print os.environ["fileName"]    #print imported var
except KeyError:
    print "Please set the environment variable" 
fileTitle=fileName + '.inp'
f=open('fileTitle', 'r')
line=f.readlines()
print line[0]

I tried with no positive results:

 import sys
var1=sys.arg[1]

and

import os
os.getenv["fileName"]

The shell and python scripts are in the same folder

Thank you in advance!

Upvotes: 0

Views: 214

Answers (1)

that other guy
that other guy

Reputation: 123750

The variable needs to be marked for export in the shell, otherwise it will not be passed to other programs:

#!/bin/bash
echo Enter the name of the file
read fileName
export fileName
python gulp.py  

Things to note:

  • The export can go anywhere as long as it's run before python. It doesn't have to be after the variable is assigned.
  • Using lowercase variable names in bash (like you're doing) is a great habit that prevents bugs. Exported variables are conventionally uppercase though. You can have both by exporting another name with that value: export FILENAME="$fileName" or using prefix assignments: FILENAME="$fileName" python gulp.py

Upvotes: 1

Related Questions