Setting variables with BASH and getting them in Python script
Over recent years I have been writing more and more automation and other scripts in Python. Many of them require input data which should be stored in an variable on the operating system, rather than somewhere else, before it is available to the Python program. Examples of this sort of input data are service URLs, usernames, passwords etc. . In this article I look at how to set variables on the command line using BASH, make them available to other command line tools using import built-in BASH command and finally how to get them in a Python script.
Setting variables with BASH
Setting variables with BASH is easy. If variable name is PASSWORD and it is assigned value pass123, it can be set on the command line as follows:
Making variables available to child processes of the current process In order for PASSWORD to become available to other programs the variable has to be marked for export. For this one uses built-in BASH command export:
Accessing environment variables in a Python script
To get access to variable PASSWORD and its value in a Python scripts, first import os module, then read the value from environ dictionary it provides.
import os print(os.environ['PASSWORD'])
Being able to read operating system variables in your Python script is an extremely useful technique and a vary common requirement today. This short article presents a quick but an effective way it can be achieved.
This post was updated on 30 Oct 2022 01:17:44
Author, Copyright and citation
Author of the this article - Sylwester Wojnowski - is a sWWW web developer. He has been writing computer code for the websites and web applications since 1998.
©Copyright, 2023 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.
Computer code, if present in the article, is excluded from the above and licensed under GPLv3.
Cite this article as:
Wojnowski, Sylwester. "Setting variables with BASH and getting them in Python script." From sWWW - Code For The Web . https://swww.com.pl//main/index/setting-variables-with-bash-and-getting-them-in-python-script