I would like to invoke the following python script in C :
#!/usr/bin/python2.7
import parser
def evaluate(text):
code = parser.expr(text).compile()
return eval(code)
as explained in the following page https://docs.python.org/2/extending/embedding.html, i can call this script from C using the pwd(path) of the file.
However, i would like to know if it's possible to not load the script by calling python on a C string directly, defining the script.
For example, i would like to let's say i put :
#define PYTHON_SCRIPT ((char*)(\
import parser\
\
def evaluate(text):\
code = parser.expr(text).compile()\
return eval(code)\
))
is it possible to call the python interpreter directly on that string?
Indeed, knowing that i need to pass text as a variable, i can't use this Pyrun_SimpleString function, and i was not able to find something to answer this question.
As mentioned in the comment there is no Pyrun_SimpleString. How to execute Python functions from C is covered here. One way to do it:
Compile your script using Py_CompileString
Create a dictionary for globals/locals.
Extract the function from your globals dict by using PyDict_GetItemString(name)
Build your arguments tuple with PyArg_ParseTuple
Execute your function object by using PyObject_CallFunction.
Take a look at Weave, it allows you to include C code directly in Python code.
Related
I'm attempting to call a C# function from a Python script, via the clr module from the PythonNet library.
One of the arguments that this C# function takes is of the type System.Collections.Generic.IEnumerable. Simply supplying a list of the required data types to the first argument results in a 'list' value cannot be converted to 'System.Collections.Generic.IEnumerable' error.
After searching online, the supposed .NET datatypes should already be included in the Python installation, and I should be able to access them. However, I'm unsure as to how.
Doing:
from System.Collections.Generic import *
Fails because the module isn't found, while doing:
import collections
Doesn't have a namespace IEnumerable.
How would I go about converting a Python list to the System.Collections.Generic.IEnumerable data type?
Thanks for reading my post, any guidance is appreciated.
Before importing anything from C#/.NET you have to import clr from pythonnet package.
After messing around in the Python script for a few hours, I managed to figure out a solution:
First, the actual C# Collections namespace has to be imported via the clr module as such:
clr.AddReference("System.Collections")
Then, the specific data type of the Collections namespace has to be imported:
from System.Collections.Generic import IEnumerable
And then one should be able to use the respective data type, and call all the class functions it has. In my case, I wanted to convert a Python List into the IEnumerable datatype. Therefore, I could iterate over my Python List, and call the Add function of the IEnumerable class (using datatype of int as an example):
myList = [1, 2, 3]
myIEnumerable = IEnumerable[int]()
for i in range(len(myList)):
myIEnumerable.Add(myList[i])
As a sidenote, while the C# function that I wanted to call from my Python script has one of its arguments listed as accepting a type of System.Collections.Generic.IEnumerable, I managed to get it to work with having a System.Collections.Generic.List type instead. Perhaps it'll be useful for someone else.
I am trying to create functions dynamically on the fly or to create functions programmatically in python and am getting stuck at this.
def test(a,b):
print(a)
#Result:
def test(a,b,c):
print(a)
print(b,c)
I am trying it with AST module and failing to understand the AST syntax for function. I understand that a function details can be fetched using functionname.__code__.xxx. But I will be unable to make changes since it is readonly. Here is what I am trying:
I tried getting the AST dump of the above function and it didnt work.
Trying to get the string version of function definition (couldnt find reference)
I have also tried the below but feel that it may be an issue somewhere like when there is a re-assignation which makes it local:
def tests(a,b):
print(a,b)
def mytest(c):
print(a,b,c)
return mytest
def tests(a,b):
print(a,b)
def mytest(c):
print(a,b,c)
a = 10 # this will become local variable
return mytest
I am on python 3.x
Any help or any other easier way?
I am stuck in resolving a problem using python. Problem is I have to pass a variable value of module(python_code1.py) to a different module(python_code2.py). Based on the variable value, need to do some calculation in the module python_code2.py and then need to capture output value in the same module(python_code1.py) for further calculations.
Below is the snapshot of my code logic :
python_code2.py
import python_code1
data = python_code1.json_data
'''
Lines of code
'''
output = "some variable attribues"
python_code1.py
import python_code2
json_data = {"val1": "abc3","val1": "abc3","val1": "abc3"}
input_data = python_code2.output
''''
Lines of code using input_data variable
'''''
when I execute python python_code1.py, this is giving error:
AttributeError: module 'python_code2' has no attribute 'output'
I feel like I am not doing it in write way, but considering my code complexity and lines of code, I have to use these 2 module method.
Putting your code at the top-level is fine for quick throw away scripts, but that's about all. The proper way to organize your code for anything non-trivial is to define functions, so you can pass values as arguments and get results as return value.
If there's only on script using those functions, you can keep them in the script itself.
If you have multiple scripts needing to use the same functions, move those functions to a module and import this module from your scripts.
I want to evaluate a string name as a function in Lua/Torch. Below is an example of what I want to do:
require 'torch'
tensorType = torch.getdefaulttensortype()
print (tensorType) -- Will print "torch.DoubleTensor"
My goal is to be able to use the string in tensorType as name of a function and evaluate that function like follow:
tensorType(some arguments)
In MATLAB and Python there is a `eval()' function which can execute arbitrary strings. Is there such a function in Lua/Torch?
How can I do that in Torch/Lua?
You can use loadstring but that's generally not recommended because it has to compile code at runtime. What is this for?
First extract the name of the field from the string:
k=tensorType:match("%.(.+)$")
Then use the name to call the function:
torch[k](some arguments)
You could also try lutorpy, you will have a lua engine in python, thus, you can load any lua/torch library, and you can run lua code with "lua.eval('torch.DoubleTensor(3,4)')". Check lutorpy for more details.
The whole scenario is like this:
there is a function setmessagelistener(a_structure,function_pointer) in my c library.
i am writing a python library which is a wrapper on above mentioned c library using Ctypes.
so what i did is something like this:
def setlistener(a_structure,function_pointer)
listenerDeclaration = CFUNCTYPE(c_void_p, c_void_p)
listenerFunction = listenerDeclaration(function_pointer)
setMsgListener = c_lib.setMessageListener
setMsgListener.argtypes = [c_void_p, c_void_p]
setMsgListener.restype = c_ubyte
if (setMsgListener(a_structure, listenerFunction)==0):
sys.exit("Error setting message listener.")
Now,another python program uses above function from my python library to do the work,but the problem is:
when i run the program it gives me segmentation fault because the local object( listenerfunction) is already garbage collected(i think so) when control returned from the library function setListener() as it being a local object.
is there any workaround/solution to this problem?or am i missing something?
please suggest...
thanx in advance
As you suspect, you need to keep a reference to listenerFunction as long as it is needed. Perhaps wrap the function in a class, create an instance and set the listenerFunction as a member variable.
See the Python documentation for ctypes callbacks, especially the important note at the end of the section.