简体   繁体   中英

how to generalize/get base directory for Linux path for python script

(Linux)in Bash I can use variableName= cd $BASEDIR./Desktop to replace HOME/userName/Destop. How can I achieve the same in Python?

EXAMPLE: need to replace home/name to be generic so that I can run this from multiple hosts. f = open("home/name/directory/subdirectory/file.cfg", "r")

You might get some use out of os.path.expanduser or os.path.expandvars :

>>> import os
>>> os.path.expanduser('~/Desktop')
'/home/userName/Desktop'

or, assuming that $BASEDIR is defined in your environment,

>>> import os
>>> os.path.expandvars('$BASEDIR/Desktop')
'/home/userName/Desktop'

Using the first option, maybe you can do what you want to do with:

f = open(os.path.expanduser("~/directory/subdirectory/file.cfg"), "r")

You can read environment variables directly from os.environ :

import os
basedir = os.environ.get('BASEDIR')

To construct a path reliably, the os module provides os.path.join . You should also provide a fallback if the variable is undefined. This could look like this:

import os
my_path = os.path.expanduser(os.path.join(
    os.environ.get('BASEDIR', '~'),  # default to HOME
    'Desktop'
)

Note that environment variables may not be the most ideal solution. Have a look at arguments, for example via the argparse module .

Try to use commands libray.

import commands

commands.getoutput("cd $BASEDIR./Desktop")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM