I've read about different variations of this problem across the website, and basically all of the solutions involve printing the Python function output instead of returning it. This is unhelpful for me because I need to be able to pass that output back to the BASH script, as one of the arguments for the kdeconnect-cli sms function later on in the script.
To give you an idea of what I'm trying to do, I'll give both scripts with annotations about what I think it should be doing. Python (contactmod.py):
def Contacts(arg): # Define the function which the BASH script will be using
if int(arg) != arg: # If the argument is not a (whole) number
contactsfile = open("contacts.txt") # contacts.txt is in the same directory as contactmod.py and Test.shq
contacts = {} # Make the number finding list
arg = arg.lower() # Convert the inputted contact name to lowercase
for line in contactsfile:
line = line.split("=") # name, number
contacts[line[0]] = line[1] # Match name and number
return (contacts[arg]) # Return phone number that is equivalent to contact name
else:
return (arg) # Return phone number (because that's what was inputted)
The format for each line of contacts.txt is as follows: contact name=telephone number
BASH (Test.sh):
text () { # Define my BASH function)
var1=$1 # Assign the first argument of text () to the variable var1
var2=$2 # Assign the second argument of text () to the variable var2
number=$(python3 -c'import contactmod; contactmod.Contacts(var1)') # Pass var1 into Contacts(), of contactmod.py, and assign the output to the variable number
echo var1 # Print what should now be a phone number
echo var2 # Print the message
}
Even though the end goal is to use kdeconnect, I'm just using echo to show me the variables and avoid more confusion than necessary.
To test this, I executed Test.sh in BASH:
$ source Test.sh
There was no output in the terminal, so I tested the newly defined text () like this:
$ text "me" "Hello"
("me" is in contacts.txt)
This caused the following error:
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'var1' is not defined
var1
var2
As the results of my Python function will be used by another algorithm, it is important that they are returned from the function and not just printed to the user. However, if printing is the only way of doing it, I would appreciate it if someone could show me what to do and explain how it works. The code's all there if you want to try it, and I'll also try, one way or another to reply to further enquiries about this problem.
This is the answer whose code I sampled while trying to solve this on my own: Calling a python function from bash script