python 导入.bashrc中的所有值作为环境变量[重复]

x759pob2  于 2023-01-04  发布在  Python
关注(0)|答案(2)|浏览(174)
    • 此问题在此处已有答案**:

os.makedirs doesn't understand "~" in my path(3个答案)
How do I open a file in python with a relative path using with open()? [duplicate](2个答案)
Python get env from finished subprocess(2个答案)
4小时前关门了。
我使用以下命令创建了一个.bashrc文件:

touch ~/.bashrc

我正在尝试让其中的所有变量都成为我当前环境中的环境变量。我在网上看到,您可以将其作为source ~/.bashrc源代码,但当我这样做时没有任何变化(我无法访问变量),但我可以运行cat ~/.bashrc,仍然将变量名视为密钥,将变量视为密码。
我还尝试将其循环为

import os

# open the .bashrc file in the home directory (~/)
with open('~/.bashrc') as f:
    # read the lines in the file
    lines = f.readlines()

# iterate over the lines in the file
for line in lines:
    # split the line into parts
    parts = line.split('=')
    # if the line has the correct format (key=value)
    if len(parts) == 2:
        # extract the key and value
        key, value = parts
        # remove any leading or trailing whitespace from the key and value
        key = key.strip()
        value = value.strip()
        # set the key as an environment variable with the corresponding value
        os.environ[key] = value

但open没有运行,因此出现错误。

FileNotFoundError: [Errno 2] No such file or directory: '~/.bashrc'

如何导入.bashrc文件中的所有变量?

58wvjzkj

58wvjzkj1#

source只在shell环境下才有意义(通常是bash shell --.是更易移植的POSIX等价物)。你不能在python脚本中有意义地使用它来更新你的环境。你必须在shell中获得包含你的环境变量的文件,然后运行python脚本--它将继承包括你的新变量在内的环境。
~也是一个shell特有的扩展(参见Tilde Expansion)。默认情况下,Python会假设~是一个文本路径名,你需要使用os.path.expanduser来执行一个类似于shell的波浪符扩展。
如果你想在python中打开并解析这个文件,你可以这样打开它:

with open(os.path.expanduser('~/.bashrc')) as f:
  lines = f.readlines()

如果可以,在运行脚本之前获取它可能会更容易:

#!/bin/bash
source ~/.bashrc
/path/to/pythonscript
mepcadol

mepcadol2#

你在尝试做相反的事情,你不需要在python中解析bash文件。
我在网上看到你可以把它作为source ~/.bashrc来源代码,但是什么都没有改变
~/.bashrc中的内容可能不正确。
示例:

# .bashrc
export MYVAR=myval
othervar=otherval
#! /usr/bin/env python3
# mypython

import os
print(os.environ)

那么

source ~/.bashrc
./mypython

打印出类似于

environ({..., 'MYVAR': 'myval', ...})

相关问题