passing values across functions yields no output - python

I have the code below where I use python package click to fetch some input from user. I then pass the user input to a function that has code to load a pre-trained model. I return a list of values that I pass to a second function that generates text using the model and other values. However the values aren't passed from first function to the second because when I try to print the list I get nothing. Could someone point out what I'm doing wrong, thanks a lot!!
#click.argument('email_template', nargs=1)
def load_model(email_template):
## code block here
list1 = [email_template, value1, value2]
return list1
def generate_text(value2):
# code block here
return result
if __name__ == '__main__':
list1 = load_model()
list2 = generate_text(list1)
print(list2)

You are missing a #click.command() decorator. It is not enough to use #click.argument(), then expect this to work. The #click.command()-decorated function becomes the entry point of your script, and should not be seen as something that'll return the user options.
Also, if email_template is the only option your script takes and it expects just one value, there is no point in using nargs=1.
So do this:
import click
#click.command()
#click.argument('email_template')
def load_model(email_template):
## code block here
# This is your *main script function*.
list1 = [email_template, value1, value2]
# don't return, continue the work you need doing from here
list2 = text_generator(list1)
print(list2)
def generate_text(result):
# code block here
return value2
if __name__ == '__main__':
load_model()
When load_model exits, your script exits.
Also, rather than use print(), consider using click.echo(), especially when you need to print text that uses non-ASCII characters and needs to work on a variety of platforms, or if you want to include ANSI colors in your output.

Related

How to reuse completions from PathCompleter in prompt_toolkit

I am creating a REPL tool for my project that (simplified for clarity) either directly executes entered commands or (if a command ".x some/path/to/file" is entered) reads and executes them from file. My question is related to auto-completing the user input (using prompt_toolkit).
I have something like (minimum executable example):
import prompt_toolkit
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.document import Document
from prompt_toolkit.contrib.completers import PathCompleter
class CommandCompleter(Completer):
def __init__(self):
self.path_completer = PathCompleter()
self.commands = [".x", "command1", "command2"]
def get_completions(self, document, complete_event):
if document.text.startswith(".x "):
sub_doc = Document(document.text[3:])
yield from (Completion(cmd.text, -document.cursor_position)
# ???????? ?????????????????????????
for cmd
in self.path_completer.get_completions(sub_doc, complete_event))
# ???????
else:
yield from (Completion(cmd, -document.cursor_position)
for cmd in self.commands
if cmd.startswith(document.text))
if __name__ == "__main__":
while True:
other_args = {}
input = prompt_toolkit.prompt(">>> ", completer=CommandCompleter(), **other_args)
# Do something with input (omitted)
The second if-branch (for commands) works correctly but I don't know how to properly call the PathCompleter.get_completions() method and reconstruct the Completion objects from its result (where the ???'s are) in the first branch. The trick is that I am using the completion only for a part of the input and various sub-stringing, position calculations etc. did not (yet) lead to the satisfactory behaviour (i.e. offering the paths and constructing the correct input line).
I will definitely go on searching but if anyone knows how to rewrite this, it would be very useful.
Note: yield from self.path_completer.get_completions(document, complete_event) would be used if the whole input would be just the path (and this works correctly).
Probably the following should fix it:
sub_doc = Document(document.text[3:])
yield from (Completion(completion.text, completion.start_position, display=completion.display)
for completion
in self.path_completer.get_completions(sub_doc, complete_event))
completion.text contains the text that is going to be inserted;
completion.start_position contains the place where the text is going to be inserted, relative to the cursor position (in this particular example we can take the value from the nested completer).
completion.display is the value displayed in the pop-up menu. (In this case, the whole filename, rather than only the inserted string.
Feel free to open a GitHub issue if you have any more questions.

How to convert user input text to programming text in python 2?

So I was writing a function for Euler's Method for solving first order differential equations. My problem is that I have to change the code every time I want to change the differential function.
Is it possible to have the user input an expression and then get the program to use that input to carry out a calculation?
def derivative(a,b):
func=a**2+b**2
return round(float(func),4)
def euler(x_in,y_in,x_fin,step):
rounder = [x_in,y_in,x_fin,step]
for i in rounder:
i=round(i,4)
x=x_in
y=y_in
while not(x==x_fin):
der=derivative(x,y)
x=round(x+step,4)
y=round(y+(der*step),4)
print y
I would like to be able to change the func variable in the derivative function on user input.
ive had this problem today and got it to work using a dictionary.
What I did is:
1st step, defining functions:
def hello():
print('Hello')
2nd step, defining dictionary:
func_dict = {'goodbye':hello}
3rd step, asking for command:
command = input('Goodmorning Sir.')
4th step, asking for the translation of input to output (goodbye->hello in this case, you can also use the same words):
func_dict[command]()
Hope this was clear enough, ill put my full code below (from a different code though) if you want to see an example.
thanks DYZ for editting at first glance.
def test():
print('Test is successfull')
def help():
pass
func_dict = {'test':test,'help':help} # In this case the 1st is the input, 2nd output
command = input('> ')
func_dict[command]()
EDIT: Maybe using .int or .float will be better in this case.

returning a specific type in Python

The quick version:
I'm trying to figure out how to pass either a list or tuple from a function in one script, to a function in another script. The issue I run into, is that it always becomes a NoneObjectType in the second script, and then I can't do anything with it other than print it out as a long string.
The long version:
I use a 3d program called Poser, that allows the use of Python to auto mate tasks. Because of this I made a nice little script called SelectMultiple that gives me a nice wxPython window were I can choose the items I want to modify. Because I can see using this over and over, I wanted it to be it's own script.
Here is the function I'm calling from SelectMultiple:
def MyApp():
title = "Select from list"
# Make the selection window pop up
mydialog = userInput(title, lst)
popupwindow = mydialog.ShowModal()
# If the user cancels win = 0
if popupwindow == wx.ID_CANCEL:
print "User canceled"
return
# Get the selected actors
selected = mydialog.GetSelectedActors()
# We are finished with the dialog
mydialog.Destroy()
return lst(selected)
by default selected is a tuple, as you can see I tried casting it as a list before returning it, but it doesn't show up that way in my other script. The file does import, and I can print it and get a string that shows the content, but it's always NoneType and I can't do much with it. Here's the script I'm calling from:
import poser
import os
scene = poser.Scene()
pathname = os.path.split(poser.AppLocation())[0]
pathname = os.path.join(pathname, 'Runtime', 'Python', 'poserScripts', 'ScriptsMenu', 'GadgetGirl')
sys.path.append(pathname)
try:
import SelectMultiple
except:
print "Could not import SelectMultiple script"
def ChoiceWindow():
title = "SuperFly Node Fixer"
message = "Choose the operation to preform"
list_of_operations = ["Delete Node", "Detach Node", "Re-Link Node"]
drop_down_window = poser.DialogSimple.AskMenu(title, message, list_of_operations)
return drop_down_window
def Controller():
script_to_run = ChoiceWindow()
#Need to call multiple so that we can know on what figures
list_of_figures = SelectMultiple.MyApp()
print type(list_of_figures)
Controller()
So yeah, how do I get something other than a NoneType back.
So I created my own issue with a typo. After I discovered that selected wasn't a list but a tuple, I mistyped the list cast as lst and then couldn't figure out why it wasn't a list. Thanks for the help
Loop thru the selected tuple and add the items into a list.
l = list()
for item in selected:
l.append(item)
return l
Also I'm not sure what version of Python you're using but the cast for list is list() not lst()

How to append function to a list then print it

I am creating a basic recipe viewer in python, I stumbled across a problem of which when I try to print my saved recipe it displays [None], as seen the recipe is firstly a function, then it is appended onto a list then I try to print it when loading it.
The code below can explain more. How do I stop the [None, None] from appearing? The code below is a sample I made which I could easily adapt to resolving my issue in my recipe rather than posting my entire code on here.
b = [] #this is meant to resemble my list
def function(): # this is meant to resemble my recipe
print("hi")
function()
a = input('write 1 = ') # this is meant to resemble the user to saving the recipe
if a == '1':
b.append(function()) # this is meant to resemble me saving the recipe onto a list
print(b) # this is meant to resemble me loading the recipe
When I run my code , sorry don't have enough reputation points to post an image but this is what comes up in the python shell
hi
write '1' = 1 #user input
hi
[None]
You are not returning anything from your function. You are printing, but that's not the same thing.
Use return to return the value:
def function():
return "hi"
print() writes to your terminal, the caller of the function is not given that output.
You can always use print() to print the return value:
print(function())

Change python command to subtract value instead of add in MYSQL

Just got one other question for my python plugin.
Here is the code:
def cmd_give(self, data, client=None, cmd=None):
"""
^3<player> <money> - Give someone however much money you want.
"""
input = self._adminPlugin.parseUserCmd(data)
if not data:
client.message('^7 correct syntax is !give <player> <money>')
return False
else:
if len([x for x in data if x.isspace()]) < 1:
client.message('^7 correct syntax is !give <player> <money>')
return False
else:
input_data = data.split(' ',1)
scname = input_data[0]
ammount = int(input_data[1])
sclient = self._adminPlugin.findClientPrompt(scname, client)
if not sclient: return False
self.earn_money(sclient, ammount)
return True
Now this obviously adds the value given in the command to the user inputting into mysql.
I'm also wanting a command to subtract any value given in the command as well.
So this command above is a give and I also want a take.
My problem is I don't know what the change is to minus the amount off the value input instead of adding.
Hope someone can help,
Thanks guys.
Without modifying the function that does the actual addition, the suggestion by Rob Watts in a comment will work:
ammount = -int(input_data[1])
You can either create a new function, cmd_take, and do that there, or have a more general function (cmd_transaction?) that takes an extra argument (eg give) and has the appropriate logic:
if not give:
ammount = -int(input_data[1])
In the first case, it would be good practice to extract most of the code to a helper function, to avoid repetition, but if you don't know python and this is just a one time thing, having a cmd_take function that is exactly like command_give, except for that one line, is the simplest solution.

Categories

Resources