Search code examples
pythonjuliacallexecutable

How to simplify a string of executable code for PyJulia


I want to use julia inside python to speed up some of the code that is slow. Therefore I installed the PyJulia package. As some Julia command are several lines long, I'm writing string of executable code that I pass to Julia. However, the strings are complex to read. Moreover, I would prefer to have as a string as I want to work in a Jupyter Notebook and want to have every piece of code visible in one file. Here is the code:

import julia
from julia import Base
from julia import Main
from julia import DataFrames

jst = "using DataFrames; \
df = DataFrame(A = [1,2,4,6], B = ['M', 'F', 'F', 'M']);\
for i in 1:length(df.A);\
    if df[i,:A] > 3;\
        println(df[i,:A]);\
    end;\
end;\
"
Main.eval(jst)

Is there a way to simplify the the string jst?

Many thanks in advance


Solution

    • I guess what you're looking for is multiline string declaration. This'll not simplify the string, rather makes it easier to read as a code snippet and fits well within the code.
    • Using """ you can declare a code snippet within your code and use it for execution.
    jst = """
    
    using DataFrames;
    df = DataFrame(A = [1,2,4,6], B = ['M', 'F', 'F', 'M']);
    for i in 1:length(df.A);
        if df[i,:A] > 3;
            println(df[i,:A]);
        end;
    end;
    
    """.strip() # remove trailing & leading spaces