how to generalize/get base directory for Linux path for python script
<p>(Linux)in Bash I can use variableName= cd $BASEDIR./Desktop to replace HOME/userName/Destop.  How can I achieve the same in Python?</p>

<p>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")</p>

<p>You can read environment variables directly from <code>os.environ</code>:</p>

<pre><code>import os
basedir = os.environ.get('BASEDIR')
</code></pre>

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

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

<p>Note that environment variables may not be the most ideal solution. Have a look at arguments, for example via the <a href="https://docs.python.org/3.5/library/argparse.html#module-argparse" rel="nofollow"><code>argparse</code> module</a>.</p>

python