my aim is to use a script written in IDL, into python:
IDL code:
PRO PS_GS
; Start the application
e = ENVI()
;Generate the roi from a vector file
; Open a vector file
file_vec = Filepath('Sic_Trapani.shp', ROOT_DIR = 'E:\mydirectory\')
vettore = e.OpenVector(file_vec)
; Get the task from the catalog of ENVITasks
Task_VtoR = ENVITask('VectorRecordsToROI')
; Define inputs
Task_VtoR.INPUT_VECTOR = vettore
; Define outputs
Task_VtoR.OUTPUT_ROI_URI = Filepath('roi_roi.xml', ROOT_DIR = 'E:\mydirectory\')
;Run the task
Task_VtoR.Execute
END
The above code, launched into IDL command prompt, works correctly.
I want make a python script that:
option 1) launch the above idl .pro script
option 2) use the IDL to Python Bridge sintax.
In the first case, using the subprocess.call("idldirectory\idl.exe") command, i can open the IDL prompt into the windows command prompt. But i can not execute any IDL function like a simple PRINT, 'hello'.
In the second case, i write the following poython code:
import subprocess
from subprocess import call
import idlpy
from idlpy import IDL
e=IDL.ENVI()
msi_file = """IDL.Filepath(mydata.tif", ROOT_DIR = 'mydirectory')"""
msi_raster = IDL.OpenRaster(msi_file)
The instruction e=IDL.ENVI() work correctly, in fact an Envi setion starts.
The instruction msi_file = """IDL.Filepath(mydata.tif", ROOT_DIR = 'mydirectory')""" work correctly.
My problem is with the OpenRaster instruction. It is an ENVI instruction and not an IDL instruction. So, IDL.OpenRaster does not work, and i do not have any solutions.
Can someone help me?
Thank you.
Lorenzo
You are halfway there. Where you went wrong was by calling the OpenRaster method as a static method on the IDL class. This isn't what you want to do. To use OpenRaster, you'll actually want to call that method on the ENVI object that you have created. For example:
e=IDL.ENVI()
msi_file = IDL.Filepath('mydata.tif', ROOT_DIR = 'mydirectory')
msi_raster = e.OpenRaster(msi_file)
Once you've created your object e, it behaves as any other python object. i.e. you can call it's methods, access properties etc. For example, to load your file into the ENVI display you could do the following:
view = e.GetView()
layer = view.CreateLayer(msi_raster)
The IDL class is just an interface that allows you to call any IDL function as a static method on the IDL class. But once you've instantiated an object, in this case e, use it as you would any other object.
Related
I want to ask about a command in Python that performs exactly like the dos() command in MATLAB. For instance, I have the following code block in MATLAB and I want to do exactly the same in Python.
**DIANA = '"C:\Program Files\Diana 10.3\\bin\\DianaIE.exe"';
MODEL = 'Input.dcp';
INPUTDIR = 'C:\Users\pc\Desktop\Thesis\PSO\';
OUTPUTDIR = 'C:\Users\pc\Desktop\Thesis\PSO\';
OUTPUT = 'FILE_OUTPUT.out';
WORKDIRINPUT = sprintf('%s%s',INPUTDIR,MODEL);
WORKDIROUTPUT = sprintf('%s%s',OUTPUTDIR,OUTPUT);
%
NAMES = sprintf('%s %s %s',DIANA,WORKDIRINPUT,WORKDIROUTPUT);
disp('Start DIANA');
dos(NAMES);
disp('End DIANA');**
To execute a block of code and get the output in python inside the code you can use a function called exec() and pass the expression or the code to be executed as a string.
This accepts the code as a string. Example..
code = 'x=100\nprint(x)'
exec(code)
Output:
100
And if you want to use the command prompt or power shell commands in python you should you a library named os in python
import os
os.system('cd document')
you can use os.path module for manipulation path and a lot more to know more about this go through this documentation OS-Documentation
import subprocess
subprocess.call(['C:\Program Files\Diana 10.3\bin\DianaIE.exe',
'C:\Users\pc\Desktop\Thesis\PSO\Input.py'])
I am new to Blender. I have created a simple project where I have added a text variable to it. The text I added here in Test. See image below.
Now, I want to call this script from the command line by to call this particular project file and pass in parameters like the text variable to display the text james instead of Test.
For example, typing the following command should give me video generated with the text james.
blender proj1.blend variable=james
Note: I am a beginner, and I hope I explained my question clearly.
Use python script, like
blender proj1.blend --python-expr "import bpy; bpy.data.curves['Text'].body = 'james'"
(if your text curve object called "Text")
Argument order is important - you want script to be executed after file is loaded.
You can find the arguments used to start blender listed in sys.argv, the same as if you were running a normal python script. Blender will ignore any arguments after --, your script can then find the -- argument and process any options after that.
blender -b --python maketext.py -- James
Then the contents of maketext.py would start with -
import bpy
import sys
idx = sys.argv.index('--') + 1
string_to_use = sys.argv[idx]
text_data = bpy.data.curves.new('txt', 'FONT')
text_data.body = string_to_use
text_obj = bpy.data.objects.new('text', text_data)
bpy.context.scene.objects.link(text_obj)
# animate and render
I have a C++ program that, through the terminal, takes a text file as input and produces another text file. I'm executing this program from a Python script which first produces said text string, stores it to a file, runs the C++ program as a subprocess with the created file as input and parses the output text file back into a Python object.
Is it possible to do this without using a subprocess call? In other words: is it possible to avoid the reading and writing and just run the C++ program inside the Python environment with the text-string as input and then capture the output, again inside the Python environment?
For code I refer to the function community_detection_multiplex in this IPython notebook.
You can use ctypes.
It requires the C++ function to be wrapped with extern "c" and compiled as C code.
Say your C++ function looks like that:
char* changeString(char* someString)
{
// do something with your string
return someString;
}
You can call it from python like that:
import ctypes as ct
yourString = "somestring"
yourDLL = ct.CDLL("path/to/dll") # assign the dll to a variable
cppFunc = yourDLL.changeString # assign the cpp func to a variable
cppFunc.restype = ct.c_char_p # set the return type to a string
returnedString = cppfunc(yourString.encode('ascii')).decode()
Now returnedString will have the processed string.
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
I have an OpenModelica model made with OMEdit. In order to get a concrete example I designed the following:
Now I would like to run the model in Python. I can do this by using OMPython. After importing OMPython and loading the files I use the following command to run the simulation:
result = OMPython.execute("simulate(myGain, numberOfIntervals=2, outputFormat=\"mat\")")
The simulation now runs and the results are written to a file.
Now I would like to run the same model but with an different parameter for the constant block.
How can I do this?
Since the parameter is compiled into the model it should not be possible to change it. So what I need is a model like that:
Is it possible to call the model from Python and set the variable "a" to a specific value?
With the command OMPython.execute("simulate(...)") I can specify some environment variables like "numberOfIntervals" or "outputFormat" but not more.
You can send more flags to the simulate command. For example simflags to override parameters. See https://openmodelica.org/index.php/forum/topic?id=1011 for some details.
You can also use the buildModel(...) command followed by system("./ModelName -overrideFile ...") to avoid re-translation and re-compilation or with some minor scripting parallel parameter sweeps. If you use Linux or OSX it should be easy to call OMPython to create the executable and then call it yourself. On Windows you need to setup some environment variables for it to work as expected.
I believe you are looking for the setParameterValue command. You can read about it here: https://openmodelica.org/download/OMC_API-HowTo.pdf
Basically you would add a line similar to OMPython.execute("setParameterValue(myGain, a, 20)") to your python script before the line where you run the simulation, so long as a is a parameter in your model.
Create one new folder in windows
In this folder put/create 2 new files file1.py and file2.bat
The file1.py content is:
import os
import sys
sys.path.insert(0, "C:\OpenModelica1.11.0-32bit\share\omc\scripts\PythonInterface")
from OMPython import OMCSession
sys.path.insert(0, "C:\OpenModelica1.11.0-32bit\lib\python")
os.environ['USER'] = 'stefanache'
omc = OMCSession()
omc.sendExpression("loadModel(Modelica)")
omc.sendExpression("loadFile(getInstallationDirectoryPath() + \"/share/doc/omc/testmodels/BouncingBall.mo\")")
omc.sendExpression("instantiateModel(BouncingBall)")
omc.sendExpression("simulate(BouncingBall)")
omc.sendExpression("plot(h)")`
the file2.bat content is:
#echo off
python file1.py
pause
then click on file2.bat... and please be patient!
The plotted result window will appear.