0

In UNIX from command line, I do

setenv HOME <path to home>

I pass it as argument to my python script

 python hello.py HOME

and do

sys.argv[1] = os.environ["HOME"] 

still it doesn't read the path.

I am new to python, is os.environ correct for this case?

Jérôme Bau
  • 707
  • 5
  • 16
geek_xed
  • 165
  • 1
  • 8
  • 15
  • why are you setting sys.argv[1] as the home environment variable? What is your complete requirement? – Anand S Kumar Jul 03 '15 at 16:33
  • My script requires path of directory as the argument. The path to directory will be different for each user (depending on different PCs). Each user sets up the environmental variable HOME to the path. It is just like common environmental variable for all users. – geek_xed Jul 03 '15 at 16:37
  • I am new to python and still learning it. I am using argparse module of python to pass the arguments along with script. the single argument I require is path to a directory, which is different for each user like user1: /home/user0123/folder , user2: /home/user8976/folder2/folder. Idea is each user will set the path to variable HOME and the script will make use of it. So my first argument passed is HOME. Therefore doing sys.argv[1] = os.environ["HOME"]. Basically sys.argv[1] should be the path of individual user. – geek_xed Jul 03 '15 at 16:42

2 Answers2

1

It seems this depends a little on your shell. For example, in Linux using bash 4.3-7ubuntu1.5:

$ export XXX="abc"
$ python
>>> import os
>>> os.environ["XXX"]
'abc'
>>> os.environ["HOME"]
'/home/alan'
ALAN WARD
  • 1,072
  • 9
  • 4
1

If your aim is to get the path of the home directory as argument, you can just make your user send it by making shell evaluate the argument before calling the script.

I have a simple script like -

import sys
print(sys.argv[1])

In Windows I call it as -

set HOME=D:\
python script.py %HOME%

The output I get is -

D:\

In Linux -

$ python hello.py $HOME

output -

/home/random/

If you want to get it from the environment variable, and you want to pass the environment variable to use as the first argument to the script, then you should change your script like -

sys.argv[1] = os.environ.get(sys.argv[1],sys.argv[1])

This would

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176