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?

3
  • why are you setting sys.argv[1] as the home environment variable? What is your complete requirement? Commented Jul 3, 2015 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. Commented Jul 3, 2015 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. Commented Jul 3, 2015 at 16:42

2 Answers 2

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

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

2 Comments

Please do remember to accept answers for your question (All of them) , by clicking on the tick mark to the left of the answer so that it becomes green , it would help the community.
Thanks. I am new to stackoverflow, wasn't knowing this.
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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.