Hello programmers of SO,
I am making a C# interface for a socketing,
The interface is made with C# but the code ressponsable for the actual socketing part is written in Python because writing that in C# Would be insanity,
i used some ironPython to execute the python code:
var engine = Python.CreateEngine();
engine.ExecuteFile(""); //directory is inside the quotes
but i need to pass some values (IP and all that jazz)
anyone know how?
I looked at How do I pass arguments to a Python script with IronPython and it would be too hard to implement so dont ask if that thread answers my question please
You could store the data as a string in some file in c sharp, and you could have a thread in python constantly looking for the information. It would know when the information has been stored in the file if a certain keyword is passed along with it. For example (if you were using a textfile with a location called location)
File.WriteAllText(location, IPAdress + "[IP]");
and here is the code for searching for it
foreach(string datainfo in File.ReadAllText(location).Split(Convert.ToChar("\n"))
{
if(datainfo.Contains("[IP]")
datainfo.Replace("[IP]","");
string Ip = datainfo;
}
I don't know how to deal with files in python but the python equivalent of the csharp code above should work.
Related
I'm currently searching for some good ways how to support the execution of custom scripts in Python.
Let me present the "problem". I would like to execute some simple scripts on the data, that would accept a fixed number of arguments and return the transformed result.
Example:
function transform(input) {
if(input == 1)
return "YES"
return "NO"
}
These scripts could be defined dynamically by the user. I have solved a similar problem some years ago in .NET by using Lua scripts and executing them dynamically and filling the data into the function using the String.format. So for example the script that user-defined looked like that:
function transform(input) {
//function logic
return transformedInput
}
return transform({0});
And the script was executed like this:
var result = Lua.run(String.format("aboveFunction", 0));
(I have simplified the function, since the original also had some helper functions for string operations, ... but this is not relevant to the question.)
I also looked into using Lua script in Python, but there doesn't seem to be any packages that have been maintained lately. If I have missed some package that is currently worked on, or someone has some better ideas on how to solve the described problem I will be very gratefull for all sugesstions :)
So I ended up with using the lupa package for executing Lua scripts in my application.
So for example, I have prepared the following Lua function:
function(input)
if input == 1 then
return "{'turn': 'ON'}"
end
return "{'turn': 'OFF'}"
end
Which is the executed in the following Python code:
from lupa import LuaRuntime
lua = LuaRuntime(unpack_returned_tuples=True)
lua_func = lua.eval("""
function(input)
if input == 1 then
return "{'turn': 'ON'}"
end
return "{'turn': 'OFF'}"
end
""")
print(lua_func(1))
This is currently enough for my use case. I have not however tried to write some helper functions for the main function.
Can anyone give me an idea about how to call Matlab function from python script using pymatlab?
Matlab, pymatlab and python are already properly installed.
I tried to run some Matlab commands from here on python script and everything works fine. But I have no idea regarding calling Matlab function from python.
For example, I have a Matlab function which will receive a string as argument and will display it and return it, like below.
function [ name ] = print_Name(first_Name)
name=first_Name;
end
Thanks in advance for your kind suggestion.
You need to first initialize a MATLAB session
import pymatlab
session = pymatlab.session_factory()
Then you can use the run method to call any MATLAB function that you wish
session.run("print_Name('name')")
Or you could assign a value in the workspace and use that
name = 'My Name'
session.putValue('name', name)
session.run('print_Name(name)')
If you want to get a value back, you can always assign the output of print_Name to a variable and call session.getValue to get that back into Python
session.run('output = print_Name(name)')
result = session.getValue('output')
That being said, I would highly recommend using The Mathwork's own library for interacting with MATLAB from Python.
I am working on an extendscript code (Adobe After Effects - but it is basically just javascript) which needs to iterate over tens of thousands of file names on a server. This is extremely slow in extendscript but I can accomplish what I need to in just a few seconds with python, which is my preferred language anyway. So I would like to run a python file and return an array back into extendscript. I'm able to run my python file and pass an argument (the root folder) by creating and executing a batch file, but how would pass the result (an array) back into extendscript? I suppose I could write out a .csv and read this back in but that seems a bit "hacky".
In After Effects you can use the "system" object's callSystem() method. This gives you access to the system's shell so you can run any script from the code. So, you can write your python script that echos or prints the array and that is essentially what is returned by the system.callSystem() method. It's a synchronous call, so it has to complete before the next line in ExtendScript executes.
The actual code might by something like:
var stdOut = system.callSystem("python my-python-script.py")
I am trying write a simple user defined function in Python that I pass a value to from Excel via Xlwings. I ran across some examples with an Add-in that you need to import user defined functions, but that seems overly complex.
Why isn't my example working?
VBA:
Function Hello(name As String) As String
RunPython ("import Test; Test.sayhi(name)")
End Function
Python (Test.py):
from xlwings import Workbook, Range
def sayhi(name):
wb = Workbook.caller()
return 'Hello {}'.format(name)
Error:
NameError: name 'name' is not defined
Make sure you're supplying the argument correctly:
RunPython ("import Test; Test.sayhi('" & name & "')")
The text inside RunPython() should be a valid python script. So the comment from "Tim Williams" is a quick solution. You just need to be careful to avoid ' character inside the name variable to break the python script.
If you need to write UDF (User Defined Function) a lot, or need to pass in value to get the output and then handle the result via VBA, try use ExcelPython instead of Xlwings.
Note, ExcelPython and Xlwings can work together, you can have both without conflict.
I think it's better you play the example to understand the difference. My understanding is limited to my knowledge, which might not be correct.
To summarize the difference:
ExcelPython needs a installer to be installed, it is good in UDF, which helps if you want to pass arguments in and out, and the function is cached in memory, so later call will be very quick.
Xlwings is simpler by just add the VBA module, no installer needed. It trigger Python in the background each time to run the script (each call starts a new process), in the script you can manipulate (read/write) Excel via COM.
I have the same question in the beginning, but later I find out using VBA in Excel side (intellisense) plus ExcelPython on UDF (simply process and return the data back) is a nice combination, so I think ExcelPython is only what I need.
As mentioned earlier, the 2 components have no conflict, you can have both. If the 2 author agree too, it is a good idea to combine them.
Please excuse what I know is an incredibly basic question that I have nevertheless been unable to resolve on my own.
I'm trying to switch over my data analysis from Matlab to Python, and I'm struggling with something very basic: in Matlab, I write a function in the editor, and to use that function I simply call it from the command line, or within other functions. The function that I compose in the matlab editor is given a name at the function definition line, and it's generally best for the function name to match the .m file name to avoid confusion.
I don't understand how functions differ in Python, because I have not been successful translating the same approach there.
For instance, if I write a function in the Python editor (I'm using Python 2.7 and Spyder), simply saving the .py file and calling it by its name from the Python terminal does not work. I get a "function not defined" error. However, if I execute the function within Spyder's editor (using the "run file" button), not only does the code execute properly, from that point on the function is also call-able directly from the terminal.
So...what am I doing wrong? I fully appreciate that using Python isn't going to be identical to Matlab in every way, but it seems that what I'm trying to do isn't unreasonable. I simply want to be able to write functions and call them from the python command line, without having to run each and every one through the editor first. I'm sure my mistake here must be very simple, yet doing quite a lot of reading online hasn't led me to an answer.
Thanks for any information!
If you want to use functions defined in a particular file in Python you need to "import" that file first. This is similar to running the code in that file. Matlab doesn't require you to do this because it searches for files with a matching name and automagically reads in the code for you.
For example,
myFunction.py is a file containing
def myAdd(a, b):
return a + b
In order to access this function from the Python command line or another file I would type
from myFunction import myAdd
And then during this session I can type
myAdd(1, 2)
There are a couple of ways of using import, see here.
You need to a check for __main__ to your python script
def myFunction():
pass
if __name__ == "__main__":
myFunction()
then you can run your script from terminal like this
python myscript.py
Also if your function is in another file you need to import it
from myFunctions import myFunction
myFunction()
Python doesn't have MATLAB's "one function per file" limitation. You can have as many functions as you want in a given file, and all of them can be accessed from the command line or from other functions.
Python also doesn't follow MATLAB's practice of always automatically making every function it can find usable all the time, which tends to lead to function name collisions (two functions with the same name).
Instead, Python uses the concept of a "module". A module is just a file (your .py file). That file can have zero or more functions, zero or more variables, and zero or more classes. When you want to use something from that file, you just import it.
So say you have a file 'mystuff.py':
X = 1
Y = 2
def myfunc1(a, b):
do_something
def myfunc2(c, d):
do_something
And you want to use it, you can just type import mystuff. You can then access any of the variables or functions in mystuff. To call myfunc2, you can just do mystuff.myfunc2(z, w).
What basically happens is that when you type import mystuff, it just executes the code in the file, and makes all the variables that result available from mystuff.<varname>, where <varname> is the name of the variable. Unlike in MATLAB, Python functions are treated like any other variable, so they can be accessed just like any other variable. The same is true with classes.
There are other ways to import, too, such as from mystuff import myfunc.
You run python programs by running them with
python program.py