Getting the result of an excel formula in python - excel

I need to open a .xlsx-file (without writing to it) in python, to change some fields and get the output after the formulas in some fields were calculated; I only know the input fields, the output field and the name of the sheet.
To write some code: Here is how it would look like if I would have created the library
file = excel.open("some_file.xlsx")
sheet = file[sheet_name]
for k, v in input_fields.items():
sheet[k] = v
file.do_calculations()
print(sheet[output_field])
Is there an easy way to do this? Wich library should I use to get the result of the formulas after providing new values for some fields?
Is there a better way than using something like pyoo, maybe something that doesn't require another application (a python library is clearly better) to be installed?
I'll just thank you in advance.

I now came up with a (very ugly) solution.
I am now reading the xml within the xlsx-file, and I am now using eval and some regular expressions to find out wich fields are needed; and I have defined some functions to run the calculations.
It works, but it would be great if there were a better solution.
If the resulting library is ready, and I don't forget to do this; I'll add a link to the library (that'll be hosted on Github) to this answer to my own question.

Related

AfterEffects Script - Create Excel data using script

nice to meet you!
I'm currently making an AfterEffect script that writes layer information to Excel, but no matter how much I research, I can't find a way to do it. If someone knows how to do it, can you tell me?
Actually, I'm Japanese and I don't understand English very well, so I used Google Translate to write the sentences, so I'm glad if it's conveyed well.
Layer information can be obtained from the API using the Layer object which can be accessed directly like so: app.project.item(index).layer(index) or by looping through a CompItem's layers like so:
var theComp = app.project.activeItem;
for (var i = 1; i <= theComp.numLayers; i++){
// layers in a comp are indexed from 1, rather than 0
theLayer = theComp.layer(i);
<do something with theLayer>
}
You can write this to a CSV XML or JSON file using the File.write() or File.writeln() methods of the File object. These can easily be imported into Excel.
Because the version of Javascript that extendscript uses dates back to 1995, it doesn't have native JSON.stringify() or XML.write() methods, so to create JSON or XML you will need Javascript implementations like this one for XML and this one for JSON. If you search for core JS polyfill for these functions there are dozens around.

Can I format variables like strings in python?

I want to use printing command bellow in many places of my script. But I need to keep replacing "Survived" with some other string.
print(df.Survived.value_counts())
Can I automate the process by formating variable the same way as string? So if I want to replace "Survived" with "different" can I use something like:
var = 'different'
text = 'df.{}.value_counts()'.format(var)
print(text)
unfortunately this prints out "df.different.value_counts()" as as a string, while I need to print the value of df.different.value_counts()
I'm pretty sure alot of IDEs, have this option that is called refactoring, and it allows you to change a similar line of code/string on every line of code to what you need it to be.
I'm aware of VSCode's way of refactoring, is by selecting a part of the code and right click to select the option called change all occurances. This will replace the exact code on every line if it exists.
But if you want to do what you proposed, then eval('df.{}.value_counts()'.format(var)) is an option, but this is very unsecured and dangerous, so a more safer approach would be importing the ast module and using it's literal_eval function which is safer. ast.literal_eval('df.{}.value_counts()'.format(var)).
if ast.literal_eval() doesn't work then try this final solution that works.
def cat():
return 1
text = locals()['df.{}.value_counts'.format(var)]()
Found the way: print(df[var].value_counts())

Executing functions stored in a string

Lets say that there is a function in my Delphi app:
MsgBox
and there is a string which has MsgBox in it.
I know what most of you are going to say is that its possible, but I think it is possible because I opened the compiled exe(compiled using delphi XE2) using a Resource Editor, and that resource editor was built for Delphi. In that, I could see most of the code I wrote, as I wrote it. So since the variables names, function names etc aren't changed during compile, there should a way to execute the functions from a string, but how? Any help will be appreciated.
EDIT:
What I want to do is to create a simple interpreter/scripting engine. And this is how its supposed to work:
There are two files, scr.txt and arg.txt
scr.txt contains:
msg_show
0
arg.txt contains:
"Message"
And now let me explain what that 0 is:
First, scr.txt's first line is function name
second line tells that at which line its arguments are in the arg.txt, i.e 0 tells that "Message" is the argument for msg_show.
I hope my question is now clear.
I want to make a simple scripting engine.
In order to execute arbitrary code stored as text, you need a compiler or an interpreter. Either you need to write one yourself, or embed one that already exists. Realistically, the latter option is your best option. There are a number available but in my view it's hard to look past dwscript.
I think I've already solved my problem! The answer is in this question's first answer.
EDIT:
But with that, as for a workaround of the problem mentioned in first comment, I have a very easy solution.
You don't need to pass all the arguments/parameters to it. Just take my example:
You have two files, as mentioned in the question. Now you need to execute the files. It is as simple as that:
read the first line of scr.txt
check if it's a function. If not, skip the line
If yes, read the next line which tells the index where it's arguments are in arg.txt
pass on the index(an integer) to the "Call" function.
Now to the function which has to be executed, it should know how many arguments it needs. i.e 2
Lets say that the function is "Sum(a,b : integer)".It needs 2 arguments
Now let the function read the two arguments from arg.txt.
And its done!
I hope it will help you all.
And I can get some rep :)

executing user input as code

I want to step through and evaluate user defined formulas in a worksheet (i.e. they would be strings).
The text may look something like (syntax could be changed to make the vba code writing easier):
Var1('a,1') = 0.1
Var1('a,2') = 0.5
Var2('a') = Var1('a,1') + Var2('a,2')
Var3('a') = SomeFunction(Var2('a'),"SomeArg")
etc.
If I could wrap each line in something like Execute(Line) then it seems straightforward, is this possible?
The only other method I've been able to think of is having a dictionary store the variables, but then I'll need to write some (probably bug filled) code to wrap the variable names but not the function names.
VarDict("Var1('a,1')") = 0.1
VarDict("Var1('a,2')") = 0.5
VarDict("Var2('a')") = VarDict("Var1('a,1')") + VarDict("Var2('a,2')")
VarDict("Var3('a')") = SomeFunction(VarDict("Var2('a')"),"SomeArg")
etc.
Possibly a little of topic but I would suggest taking a look at pyspread it is a spreadsheet that allows each cell to be any python object up to and including a full python program - if you are not tied into Excel then you will find a lot of the work done for you.
N.B. python, pyspread and all the required tools, (wxpython for the GUI, numpy for the numeric libraries, gpg for signing spreadsheets securely, etc), are free, (including for commercial use), and will run on multiple platforms including Windows, Macintosh and Linux amongst others.

How to get the filename and line number of a particular JetBrains.ReSharper.Psi.IDeclaredElement?

I want to write a test framework extension for resharper. The docs for this are here: http://confluence.jetbrains.net/display/ReSharper/Test+Framework+Support
One aspect of this is indicating if a particular piece of code is part of a test. The piece of code is represented as a IDeclaredElement.
Is it possible to get the filename and line number of a piece of code represented by a particular IDeclaredElement?
Following up to the response below:
#Evgeny, thanks for the answer, I wonder if you can clarify one point for me.
Suppose the user has this test open in visual studio: https://github.com/fschwiet/DreamNJasmine/blob/master/NJasmine.Tests/SampleTest.cs
Suppose the user right clicks on line 48, the "player.Resume()" expression.
Will the IDeclaredElement tell me specifically they want to run at line 48? Or is it going to give me a IDeclaredElement corresponding to the entire class, and a filename/line number range for the entire class?
I should play with this myself, but I appreciate tapping into what you already know.
Yes.
The "IDeclaredElement" entity is the code symbol (class, method, variable, etc.). It could be loaded from assembly metadata, it could be declared in source code, it could come from source code implicitly.
You can use
var declarations = declaredElement.GetDeclarations()
to get all AST elements which declares it (this could return multiple declarations for partial class, for example)
Then, for any IDeclaration, you can use
var documentRange = declaration.GetDocumentRange()
if (documentRange.IsValid())
Console.WriteLine ("File: {0} Line:{1}",
DocumentManager.GetInstance(declaration.GetSolution()).GetProjectFile(documentRange.Document).Name,
documentRange.Document.GetCoordsByOffset(documentRange.TextRange.StartOffset).Line
);
By the way, which test framework extension are you developing?
Will the IDeclaredElement tell me specifically they want to run at
line 48?
Once more: IDeclaredElement has no positions in the file. Instead, it's declaration have them.
For every declaration (IDeclaration is a regular AST node) there is range in document which covers it. In my previous example, I used TextRange.StartOffset, though you can use TextRange.EndOffset.
If you need more prcise position in the file, please traverse AST tree, and check the coordinates in the document for specific expression/statement

Resources