简体   繁体   English

如何在 python 脚本中使用 shell 变量

[英]How to use shell variables within a python script

I'd like to get shell variable content to be used within a python script , specifically to get path out of it to be used later for a function call to a python script located at another directory, using sys.path.insert我想获取要在 python 脚本中使用的shell 变量内容,特别是从中获取路径,以便稍后使用sys.path.insert调用位于另一个目录的 python 脚本的函数

Let's assume my shell variable is called SHELL_VAR1 , and I want to concatenate to it /scripts folder name, so I get flow like that - using in this example os.environ.get just to illustrate my need in case it was environment variable and not a shell variable - and the question is what should be used instead:让我们假设我的 shell 变量被称为SHELL_VAR1 ,我想连接到它/scripts文件夹名称,所以我得到了这样的流程 - 在这个例子中使用os.environ.get只是为了说明我的需要,以防它是环境变量而不是一个 shell 变量 - 问题是应该使用什么来代替:

python -c 'import os; import sys;var1=os.environ.get('SHELL_VAR1'); sys.path.insert(1, 'var1' ''/scripts'');' 

A shell variable and environment variable are the same thing, in my understanding.根据我的理解,shell 变量和环境变量是一回事。

You can use pathlib for OS-agnostic filepath operations (like joining filepaths).您可以将pathlib用于与操作系统无关的文件路径操作(例如加入文件路径)。

import os
from pathlib import Path
import sys

# This will raise a KeyError if the key is not in os.environ.
var1 = os.environ["SHELL_VAR1"]
path = Path(var1) / "scripts"
sys.path.insert(1, str(path))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM