简体   繁体   中英

Is there any way to import a python file inside a shell script and use the constants present in python file inside shell script?

I want to use the constants present in python file inside a shell script.Have shared both the files code. Am trying to change the host name of the raspberry pi from 'raspberry' to 'ash' using a shell script.But I don't want to hard code the name in shell script.I have a constants.py file where I want to store all the constants.

.sh

sed -i 's/raspberry/ash/' hostname
sed -i 's/raspberry/ash/' hosts

constants.py

a = "ash"

I want to use this 'a' in shell script instead of 'ash'

Thanks for the help!

You can replace ash in the shell script with a unique formatted string (for example {} ) that you can use the replace function in Python code to replace any occurrences of that formatted string with the desired hostname ( a variable) when reading the content of the shell script into Python string. After you read and replace the string of the shell script with the desired hostname, you can overwrite the script with that updated string

Shell script (test.sh):

sed -i 's/raspberry/{}/' hostname
sed -i 's/raspberry/{}/' hosts

Python script:

a = "ash"

filename = "test.sh" # shell script to replace hostname
# Read file content into string and replace the formatted string with the desired hostname
with open(filename, 'r') as fl:
    content = fl.read().replace('{}', a)

# Overwrite the shell script with the updated string
with open(filename, 'w') as fl:
    fl.write(content)

Edit: Alternatively, if you know that the variable is stored in the constants.py script in the same directory as the shell script, you can use the command python3 -c "import constants; print(constants.<variable>)" to get the variable name from constants.py and output it to stdout and then you can store the output in a variable, say a , that you can use in the sed commands

a=$(python3 -c "import constants; print(constants.a)")
sed -i "s/raspberry/$a/" hostname
sed -i "s/raspberry/$a/" hosts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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