Setting variables with BASH and getting them in Python script

Setting variables with BASH and getting them in Python script

Created:30 Oct 2022 01:46:30 , in  Host development,  Web development

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:


PASSWORD=pass123

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:

export PASSWORD

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'])

Conclusion

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

Tags:  BASH ,  Python 


Author, Copyright and citation

Author

Sylwester Wojnowski

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.

Copyrights

©Copyright, 2024 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.

Citation

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

Add Comment

Allowed BB Code - style tags: [b][/b], [i][/i], [code=text][/code],[code=javascript][/code],[code=php][/code],[code=bash][/code],[code=css][/code],[code=html][/code]


I constent to processing my data given through this form for purposes of a reply by the administrator of this website.

Recent Comments

Nobody has commented on this post yet. Be first!