从Python

时间:2018-05-03 06:19:05

标签: python bash python-2.7

在shell脚本中,我能够导出变量。我如何在Python中做同样的事情

Shell代码:

PYTHON_PATH=`which python`    
PYTHON_PATH=`dirname $PYTHON_PATH`    
PATH=/bin:/usr/bin    
export PATH=~/.local/bin:$PATH:$PYTHON_PATH

Python代码:(版本 - 2.7)

PYTHON_PATH = subprocess.check_output("which python", shell=True)    
PYTHON_PATH = os.path.dirname(PYTHON_PATH)    
PATH = os.path.expanduser('~') + "/.local/bin:" + PATH + ":" + PYTHON_PATH    
subprocess.call('export PATH="{}"'.format(PATH), shell=True)

这是在python中导出PATH变量的正确方法。

1 个答案:

答案 0 :(得分:0)

这是否回答了您的问题(来源:this question/answer)?

import subprocess
import os

PYTHON_PATH = subprocess.check_output("which python", shell=True)    
PYTHON_PATH = os.path.dirname(PYTHON_PATH)    

os.environ["PATH"] += os.pathsep + PYTHON_PATH.decode()