从bash导出变量并在Python中使用它

Geo*_*nov 3 python linux bash shell

我正在尝试编写一个脚本,该脚本正在Linux服务器上执行几个操作,我想对大多数Linux特定命令使用bash,而对最复杂的东西仅使用Python,但是为此,我需要从bash脚本中导出一些变量并在python脚本中使用它们,但我没有找到一种方法。因此,我尝试创建两个非常小的脚本来测试此功能:1.sh是bash脚本

#!/bin/bash

test_var="Test Variable"
export test_var
echo "1.sh has been executed"
python 2.sh
Run Code Online (Sandbox Code Playgroud)

2.sh是Python脚本:

#!/usr/bin/env python3

print("The python script has been invoked successfully")
print(test_var)
Run Code Online (Sandbox Code Playgroud)

您可以猜测,当我执行第一个脚本时,第二个脚本会失败,并显示有关未知变量的错误:

$ ./1.sh
1.sh has been executed
The python script has been invoked successfully
Traceback (most recent call last):
  File "2.sh", line 4, in <module>
    print(test_var)
NameError: name 'test_var' is not defined
Run Code Online (Sandbox Code Playgroud)

之所以尝试这样做,是因为我对bash更加满意,并且我想在bash中使用$ 1,$ 2变量。在Python中也可以吗?

[编辑]-我刚刚发现如何在Python中使用$ 1和$ 2。您需要使用sys.argv[1]和sys.argv[2]并导入sys模块import sys

Or *_*uan 6

要使用 Python 脚本中的环境变量,您需要调用:

import os
os.environ['test_var']
Run Code Online (Sandbox Code Playgroud)

os.environ是一个包含所有环境变量的字典,您可以使用 dict 的所有方法。例如,你可以写:

os.environ.get('test_var', 'default_value')
Run Code Online (Sandbox Code Playgroud)


Ris*_*eke 5

检查python扩展名,它应该是.py而不是.sh 1.sh

#!/bin/bash
 test_var="Test Variable"
 export test_var
 echo "1.sh has been executed"
 python 2.py
Run Code Online (Sandbox Code Playgroud)

os库将为您提供访问环境变量的权限。以下python代码将为您提供所需的结果,

#!/usr/bin/env python3
import os
print("The python script has been invoked successfully")
print(os.environ['test_var'])
Run Code Online (Sandbox Code Playgroud)

检查参考:如何从Python访问环境变量?