I am attempting to store a list of commands to send down a serial cable using deque in Python.
My function "send_command" accepts 3 values; The command, an int. pause and a boolean wait. its definition is as follows.
def send_command(self, command, pause=0, wait=False):
What I would like to do is, rather than calling this function like so:
send_command("A234", 5, True)
... or...
send_command("B4242")
I'd like to be able to store up commands inside a deque list and use the popleft function to then call my function. This would allow me to do things such as:
CommandList = deque((['A234', 5, True], ['B4242']))
...and use the deque.append() as a way to keep adding things to the list, which would then in turn be sent to my send_command function. I could then drop in and out of the list new commands when they are needed (or as quickly as the serial part of my code can do).
The part I'm struggling with is actually using the CommandList.popleft, or any part of the deque list as the args for my send_command function. It doesn't seem as straight forward as:
send_command(CommandList.popleft)
I'm sure it's something simple, but I cannot figure it out.
Can anyone help?
Thank-you kindly.
Andy
probably you need something like:
obj.send_command(*CommandList.popleft())
That is, call popleft and use the result as an argument list for send_command. self argument suggests this is a member function, so you need to call it on an object
Another way, as I wrote in the comment, is to store prepared functions with something like this:
def make_command(obj, *args, **kwargs):
def f():
obj.send_command(*args, **kwargs)
return f
Then you can do
queue.append(make_command(obj, 'ABC', whatever='else'))
and then execute:
command = queue.popleft()
command()
unbeli is right - you need the () to call the function, and you need * to unpack the arguments. However, there's no need for using deque when you can just do this:
commandlist = [['A234', 5, True], ['B4242'], ['A234', 0]]
for command in commandlist:
send_command(*command)
and that will work perfectly fine. For more info, see unpacking argument lists.
Queues are really only necessary if you're doing something in which you want to consume the values - say you want your commandlist to be empty when you're done. Of course you could also do the same thing with a list:
q = [1,2,3,4]
while q:
print q.pop(0)
print q
HTH
Have you tried:
send_command(CommandList.popleft()) # note the ()
Related
So I have a function that returns a value. I'd like it to write it into shell only when called with print.
So c.function() doesn't return anything, while print(c.function) returns the value I need
Edit: I probably worded the question wrong
I have a class function that goes over an iterable, performs different tasks based on elements of the iterable. After completing the tasks it returns a number of the tasks completed. I need the function to write into shell only when called as print(c.function(iterable)), and to show nothing when called as c.function(iterable), is that possible?
Thanks in advance
If you write a function like,
def foo():
a = "This works."
return a
then call the function in the script like
foo()
nothing gets printed.
However, if you assign the function return call to a variable like
b = foo()
and print(b), then you get the result printed.
Simply assign to a dummy variable when you want to hide the output:
>>> _ = c.function()
And call the function normally when you want to view the output:
>>> c.function()
'the value you need'
Just in case you need to view the result, you can:
>>> _
'the value you need'
Although _ is also used in some Python shells as a special variable for the last value evaluated, so this might not always work. You might be able to rig up a fancy solution by assigning to a simple name that points to a property that appends to a list, but that seems like a lot of effort.
FWIW IPython can be made to not echo the value with a semicolon (e.g. 1; doesn't print anything) or can be set to not automatically echo values plus it automatically records every input and output.
I'm working on a project where I am making a command line to learn how to use curses in Python. I am starting to work on the interpreter for the commands, but have a situation I want to see if there is a better solution.
I want to split the string input into a command and arguments. Here's an example of how I could do it:
def processor(inputText):
command, arguments=inputText.split(' ')[0], inputText.split(' ')[1:]
I could do it this way, but because I'm picky/weird I don't like having inputText.split(' ') twice. Here's another option I could choose to shorten it:
def processor(inputText):
inputTextSplit=inputText.split(' ')
command, arguments=inputTextSplit[0], inputTextSplit[1:]
Since we're shortening code, inputTextSplit is longer so replacing it with i could be 'better':
def processor(inputText):
i=inputText.split(' ')
command, arguments=i[0], i[1:]
My issue with this though, is using shorter variables like i could cause overwriting other variables later (like using i in a for loop like for i in array:). This would make code look cleaner, but at the same time could cause issues if not careful.
Is there a way to take sections of splits of an array to variables? For example, in TI-Basic you can pass a list as an argument for an operation. To get multiple outputs of a graph function in TI-Basic would look like:
"If Y₁ is 2x, then the results would be as follows:"
Y₁({1, 3})
"{2, 6}"
{Y₁(1), Y₁(3)}
"{2, 6}"
Is there a similar way to do something hypothetical like this:
def processor(inputText):
command, arguments=inputText.split(' ')[[0,1:]]
Is there some advanced Python technique that can accomplish this, or is just an lazy idea? The expected result for an input like 'command arg1 arg2' would be ['command', ['arg1', 'arg2']].
This concept isn't something I want to limit to my project example, either. Another example could be array[[0,1:6,7:8,9:]] which would give another array with 4 values, parts of the original.
Also, I am on Python 2.7. Thanks in advance for your advice.
You can simply do:
def processor(inputText):
command, *arguments = inputText.split(' ')
return command, arguments
print(processor('command arg1 arg2 arg3'))
# ('command', ['arg1', 'arg2', 'arg3'])
Using *arguments will assign all remaining parts of the list generated by split, after the first one has been assigned to command, to the arguments list.
You can have a look at PEP 3132 -- Extended Iterable Unpacking for details on this syntax.
I am trying to make a function's output behave as if it's my input. The goal is to make a new output from the old output.
I have some code that looks like this:
def func():
BLOCK OF CODE
func()
There is no return statement in the function and no parameters within the parenthesis.
When I type func() to call my function as shown above, I get the desired output, which is a bunch of printed statements. Now I want to do something with that output to get another output.
All I'm trying to do is effectively "pipe" the output of one function into the input of another function (or, if possible, not even worry about creating another function at all, and instead doing something more direct). I looked into Python 3 writing to a pipe
but it did not help me. I also tried defining another function and using the preceding function as a parameter, which did not work either:
def another_func(func):
print another_statement
another_func(func)
I also tried making a closure (which "kind" of worked because at least it printed the same thing that func() would print, but still not very encouraging):
def func():
def another_func():
print another_statement
BLOCK OF CODE
another_func()
Finally, I tried designing both a decorator and a nested function to accomplish this, but I have no parameters in my function, which really threw off my code (didn't print anything at all).
Any advice on how to manipulate a function's output like as if it is your input so that it's possible to create a new output?
You could achieve this by redirecting stdout using a decorator:
from StringIO import StringIO
import sys
def pipe(f):
def decorated(*args, **kwargs):
old,sys.stdout = sys.stdout,StringIO()
try:
result = f(*args, **kwargs)
output = sys.stdout.getvalue()
finally:
sys.stdout = old
return result, output
return decorated
You could then get the result, output pair from any decorated function, eg:
#pipe
def test(x):
print x
return 0
test(3) -> (0, '3\n')
However, I can't think of a good reason why you'd want to do this.
(Actually, that's not quite true; it is handy when writing unit tests for user IO, such as when testing student assignments in a software engineering course. I seriously doubt that that's what the OP is trying to do, though.)
Return the desired value(s) from the function - instead of printing the values on the console, return them as strings, numbers, lists or any other type that makes sense. Otherwise, how do you expect to "connect" the output of a function as the input to another, if there is no output to begin with?
Of course, printing on the console doesn't count as output unless you're planning to eventually use OS pipes or a similar mechanism to connect two programs on the console, but keep things simple! just use the function's return values and worry about pipes later if and only if that's necessary for your problem in particular.
After reading the comments: "connecting" two functions by printing on the console from one and reading from the console from the other would be a really bad idea in this case, first you have to grasp the way functions return values to each other, trust me on this one: you have to rethink your program! even though other answers (strictly speaking) answer your original question, that's absolutely not what you should do.
just for fun ... because OP asked for it
import StringIO
import sys
def func1():
for i in range(1,10):
print "some stuff %d"%i
def func2(func):
old_std = sys.stdout
sys.stdout = StringIO.StringIO()
try:
func()
return sys.stdout.getvalue().splitlines()
finally:
sys.stdout = old_std
print func2(func1)
You need to return a value from your function. This can be used to assign the value into another variable.
Say I define some function doubleThis that will double the input
def doubleThis(x):
print 'this is x :', x
return x * 2 # note the return keyword
Now I can call the function with 3, and it returns 6 as expected
>>> doubleThis(3)
this is x : 3
6
Now I have another function subtractOne that returns the input value, minus 1.
def subtractOne(i):
print 'this is i :', i
return i - 1
Now comes the answer to your question. Note that we can call the first function as the input to the second, due to the fact that it has a return value.
>>> subtractOne(doubleThis(3))
this is x : 3
this is i : 6
5
Now i use twisted.soap to build my soap server, I'd like to build a function with plural arguments like this:
def soap_searchFlight(self,name=None,startpoint=None,destination=None):
d=Deferred()
d.addCallback(functions.searchFlight)
d.addErrback(functions.failure)
print "name"+name
print "startpoint"+startpoint
print "destination"+destination
requestdic={"name":name,"startpoint":startpoint,"destination":destination}
print requestdic
d.callback(requestdic)
return d.result
and I wrote a script to test :
import SOAPpy
import twisted
p = SOAPpy.SOAPProxy('http://localhost:7080/')
p.config.dumpSOAPOut=1
p.config.dumpSOAPIn=1
print p.searchFlight(name='3548',startpoint="北京飞机场",destination="上海飞机场")
It gives me back like this:
name上海飞机场
startpoint北京飞机场
destination3548
it looks like the args order are totally wrong so what happens and how can i ensure the right order ?
Without seeing functions.searchFlight, it's a little hard to tell, but it appears that you're passing a dict to in in a callback, then assuming that the items in the dict are in a particular order (they're not).
Change the signature of functions.searchFlight to take a tuple, and call it with a tuple in the order you want. (or pass in an ordered dict...or don't assume the dict's items are in the order that you created it in).
I'm currently working on an experiment where I'm implementing an interpreter for an old in-game scripting language. It's a forth based language, so I figure it would be fairly easy to just have the instructions (once verified and santized) put into a big list.
Once I've got the code in a list, I am trying to iterate through the entire program in a for loop that processes the instructions one at a time. Certain items, like strings, could be placed onto a variable that holds the current stack, which is easy enough. But where I'm stuck is making commands happen.
I have a big list of functions that are valid and I'd like it to where if any instruction matches them, it calls the associated function.
So, for example, if I had:
"Hello, world!" notify
...the code would check for notify in a list and then execute the notify function. The bottom line is: How do I translate a string into a function name?
You could keep a dictionary of functions the code can call, and then do a look up when you need to:
def notify(s):
print(s)
d = {"notify": notify}
d["notify"]("Hello, world!")
You can do it through locals which is a dictionary with th current local symbol table:
locals()["notify"]()
or though globals which returns a dictionary with the symbol table of globals:
globals()["notify"]()
You can give arguments too e.g.:
locals()["notify"]("Hello, world!")
or
globals()["notify"]("Hello, world!")
If you have a dict called commands that maps names to functions, you can do it like this:
def my_notify_function():
print(stack.pop)
commands = {'notify': my_notify_function, ...}
for item in program:
if item in commands:
commands[item]()
else:
stack.push(item)
Something like:
import re
class LangLib(object):
pattern = re.compile(r'"(.*?)" (.*)')
def run_line(self, line):
arg, command = re.match(LangLib.pattern, line).groups()
return getattr(self, command)(arg)
def notify(self, arg):
print arg
Then your engine code would be:
parser = LangLib()
for line in program_lines:
parser.run_line(line)
Create a dictionary of function names and some tags.
I have tried it several times before, it works really well.