[英]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. (Linux)在Bash中,我可以使用variableName = cd $ BASEDIR。/ Desktop替换HOME / userName / Destop。 How can I achieve the same in Python?
如何在Python中实现相同目标?
EXAMPLE: need to replace home/name to be generic so that I can run this from multiple hosts. 示例:需要替换home / name为通用名,以便我可以从多个主机运行它。 f = open("home/name/directory/subdirectory/file.cfg", "r")
f =打开(“主目录/名称/目录/子目录/file.cfg”、“r”)
You might get some use out of os.path.expanduser
or os.path.expandvars
: 您可能会从
os.path.expanduser
或os.path.expandvars
得到一些使用:
>>> import os
>>> os.path.expanduser('~/Desktop')
'/home/userName/Desktop'
or, assuming that $BASEDIR
is defined in your environment, 或者,假设您的环境中定义了
$BASEDIR
,
>>> 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
: 您可以直接从
os.environ
读取环境变量:
import os
basedir = os.environ.get('BASEDIR')
To construct a path reliably, the os
module provides os.path.join
. 为了可靠地构建路径,
os
模块提供了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 . 查看参数,例如通过
argparse
模块 。
Try to use commands libray. 尝试使用libray命令。
import commands
commands.getoutput("cd $BASEDIR./Desktop")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.