I want to use exec() function to execute a child script inside the main script. but I wanted to do so with other strings in combination but since the exec() command is a nonetype I'm unable to concatenate the output of the child script in the parent script.
exec is to be avoided most of the time because it leads to code that's difficult to understand and maintain. You really can get away with not using it as there are better approaches.
If your other script is a Python script, it seems like you have parts that you want to reuse in multiple places. Can't you then put those parts in functions, or classes (as appropriate) and then import them in the places you need them?
Also, if the other problem is that the code you want to reuse is printing then there's a way to remedy that: have your functions return values instead and do the printing all in one place at the end. Obviously printing doesn't give you the value to use later, it just outputs it to the console (or wherever else). That is, it performs a side effect. Functions that just take inputs and return values (and thus do not perform side effects) are called pure. The good thing about such pure functions is that you can glue them together (aka "compose" them).
Related
As mentioned in a previous question (How to examine a gdb.Type) I'm writing some specialized gdb scripting in python.
I want to call a function pointer, obtained from the inferior process, on a value, also obtained from the inferior process, and get the returned result as a gdb.Value. How?
One possibility is to convert everything to strings and convenience variables, then use gdb.execute() to perform a CLI print command, (e.g. p $2($1) ) which will make a new convenience variable, then get the convenience variable. This seems roundabout and error-prone. Is there a better way?
Some python-2.7 and python-3.x functions have the same name, but perform differently. Can I import use a py2.7 function in python-3.x one, by changing its name?
The motivating example is python-2.7's "print", i.e. print "TEXT" which does not use without parenthesis, compared to print("TEXT") in python 3. Can I keep the python 2 "print" by binding it to something like pr?
(By the way, the issue for me is typing and escaping the brackets. The keys ( and ) are harder to press than a space bar. Also, because my IDE puts them in automatically, I then need to move my cursor out of it.)
Note: I asked this previously, yet has been wrongly marked as a duplicate.
Again, to be clear, I'm specifically asking if I can bind a python 2 function to a new name in order to use its functionality in python-3.x.
Can I bind python-2.7's `print` in python-3.x, allowing me to use `print` without parenthesis in python-3.x?
I do not know how to contact moderators via internal message or correct this wrongful flag.
The real solution is to configure your IDE, rather than try and hack your way around those configuration problems.
That said, the Python 2 print statement with a space and no parenthesis does not exist in Python 3. While you can find ways to use the function from Python 2, the syntax cannot be used.
If your real problem is with the parentheses in print() for python 3, then no, as far as I know there's not really a solution. If it's a different function, you could always do
def funcName(arg):
return anotherFunc(arg)
or as chepner comments
funcName = anotherFunc
effectively renaming anotherFunc().
As for your IDE specific issues, there's probably a way to turn off the automatic parentheses (or you could just use the arrow keys on your keyboard) and the more you use the parentheses, the faster you'll get using them, which is probably a good thing, as they're used in basically every function you'll ever use.
Finally, it's best not to force a language to do a specific thing that it doesn't really provide for. You don't use GOTOs in Python - they're not built in for a reason. You can write them using other methods. You use parentheses in python 3 - don't try to change that! There's another reason not to alter a language in the way you're describing - it decreases the readability of your code. Everyone will know what you mean when you write
''.join(something)
but not when you write
randomFuncName(something)
and then in some obscure spot you have a function like the one described above that renames ''.join.
I am implementing a workflow management system, where the workflow developer overloads a little process function and inherits from a Workflow class. The class offers a method named add_component in order to add a component to the workflow (a component is the execution of a software or can be more complex).
My Workflow class in order to display status needs to know what components have been added to the workflow. To do so I tried 2 things:
execute the process function 2 times, the first time allow to gather all components required, the second one is for the real execution. The problem is, if the workflow developer do something else than adding components (add element in a databases, create a file) this will be done twice!
parse the python code of the function to extract only the add_component lines, this works but if some components are in a if / else statement and the component should not be executed, the component apears in the monitoring!
I'm wondering if there is other solution (I thought about making my workflow being an XML or something to parse easier but this is less flexible).
You cannot know what a program does without "executing" it (could be in some context where you mock things you don't want to be modified but it look like shooting at a moving target).
If you do a handmade parsing there will always be some issues you miss.
You should break the code in two functions :
a first one where the code can only add_component(s) without any side
effects, but with the possibility to run real code to check the
environment etc. to know which components to add.
a second one that
can have side effects and rely on the added components.
Using an XML (or any static format) is similar except :
you are certain there are no side effects (don't need to rely on the programmer respecting the documentation)
much less flexibility but be sure you need it.
First of all, I'm not sure I'm asking for something that is doable.
Sometimes, when I have to do some refactoring in a large codebase, I need to change the output or even the signature of a certain function. Before than I do that, I have to make sure that that output is handled correctly by the other functions that are going to call it.
The way I do it is by searching for the function name, say get_timezone_from user and then I see that function is used by two other functions called format and change_timezone_for_user. And I start looking for where those two functions are used etc... until I end up with a graph where each path looks like a stacktrace.
There are two problems.
The first one is that doing this manually is pretty time consuming.
The second is that when I look at all occurrences of a function name like format, I will often find occurences of the word format in different contexts. It can be a comment or even another function defined somewhere else.
My question is simple:
Is there an IDE or a tool that allows to find where in your code a certain function is called? Even better would be if that tool is recursive so that it draws the whole graph.
I'm trying to achieve this in Python if that helps.
I'm developing a system that operates on (arbitrary) data from databases. The data may need some preprocessing before the system can work with it. To allow the user the specify possibly complex rules I though of giving the user the possibility to input Python code which is used to do this task. The system is pure Python.
My plan is to introduce the tables and columns as variables and let the user to anything Python can do (including access to the standard libs). Now to my problem:
How do I take a string (the user entered), compile it to Python (after adding code to provide the input data) and get the output. I think the easiest way would be to use the user-entered data a the body of a method and take the return value of that function a my new data.
Is this possible? If yes, how? It's unimportant that the user may enter malicious code since the worst thing that could happen is, that he screws up his own system, which is thankfully not my problem ;)
Python provides an exec() statement which should do what you want. You will want to pass in the variables that you want available as the second and/or third arguments to the function (globals and locals respectively) as those control the environment that the exec is run in.
For example:
env = {'somevar': 'somevalue'}
exec(code, env)
Alternatively, execfile() can be used in a similar way, if the code that you want executed is stored in its own file.
If you only have a single expression that you want to execute, you can also use eval.
Is this possible?
If it doesn't involve time travel, anti-gravity or perpetual motion the answer to this question is always "YES". You don't need to ask that.
The right way to proceed is as follows.
You build a framework with some handy libraries and packages.
You build a few sample applications that implement this requirement: "The data may need some preprocessing before the system can work with it."
You write documentation about how that application imports and uses modules from your framework.
You turn the framework, the sample applications and the documentation over to users to let them build these applications.
Don't waste time on "take a string (the user entered), compile it to Python (after adding code to provide the input data) and get the output".
The user should write applications like this.
from your_framework import the_file_loop
def their_function( one_line_as_dict ):
one_line_as_dict['field']= some stuff
the_file_loop( their_function )
That can actually be the entire program.
You'll have to write the_file_loop, which will look something like this.
def the_file_loop( some_function ):
with open('input') as source:
with open('output') as target:
for some_line in source:
the_data = make_a_dictionary( some_line )
some_function( the_data )
target.write( make_a_line( the_data ) )
By creating a framework, and allowing users to write their own programs, you'll be a lot happier with the results. Less magic.
2 choices:
You take his input and put it in a file, then you execute it.
You use exec()
If you just want to set some local values and then provide a python shell, check out the code module.
You can start an instance of a shell that is similar to the python shell, as well as initialize it with whatever local variables you want. This would assume that whatever functionality you want to use the resulting values is built into the classes you are passing in as locals.
Example:
shell = code.InteractiveConsole({'foo': myVar1, 'bar': myVar2})
What you actually want is exec, since eval is limited to taking an expression and returning a value. With exec, you can have code blocks (statements) and work on arbitrarily complex data, passed in as the globals and locals of the code.
The result is then returned by the code via some convention (like binding it to result).
well, you're describing compile()
But... I think I'd still implement this using regular python source files. Add a special location to the path, say '~/.myapp/plugins', and just __import__ everything there. Probably you'll want to provide some convenient base classes that expose the interface you're trying to offer, so that your users can inherit from them.