Python in Latex

    Using Python in LaTeX would be very convenient. I immediately warn that the proposed methods are considered unsafe, because Python can crap if you write the appropriate code, so check it (=

    There is a ready-made method in the form of a stylesheet, it is used like this:
    \ usepackage {python}
    \ begin {python}
    from math import sin
    a = sin (5)
    c = sin (9)
    b = max (a, c)
    print b
    \ end {python}


    This package, in fact, creates jobname.py, writes the output to jobname.py.out, jobname.py.err, and reads it.
    The method is bad in that the variables are not saved from code to code, and for this you have to use pickle, you have to import everything again, etc., and it seems to me that it is convenient to have all the calculations in one place in a separate file so I built my lunapark ...

    Everything is very simple. Add the following to the preamble:
    \ newcommand {\ python} [1] {%
    \ immediate \ write18 {python # 1> ./py.out 2> ./py.err}
    \ immediate \ input "py.out"}
    \ newcommand {\ ptn} [1] {%
    \ python {./ path_to_your_scripts / script_name.py # 1}}
    \ newcommand {\ peval} [1] {%
    \ python {-c "print # 1" | ./path_to_your_scripts/sedder}}
    \ newcommand {\ comments} [1] {}


    The first macro calls python with the arguments you specify, the second runs a specific script with arguments, and the third can execute single-line Python code, which is then pre-converted with small sed to replace the dots with commas. And the last macro added that it would be clear where the problem was with Python output and some errors appeared in Latex.

    In the script, I have a little trick for beautiful output (true only for the mathematical environment), well, I can share gray hair too (naturally sed will only work if you have one).

    sedder:


    #! / bin / sh
    sed -e 's /\./,/'
    # Make it executable.


    end of file "./path_to_your_scripts/script_name.py":


    import sys
    from re import sub
    from __future__ import division
    def toStr (num, digitsAfter = 2):
        """Num to string with zero stripping"""
        frmt = '%.' + str(digitsAfter) + 'f'
        num = (frmt%num)
        num = num.strip('0')
        if num[0] =='.':
            num = '0'+num
        if num[-1] == '.':
            num = num.strip('.')
        return num
    def tenpower(num,maximum=1e3,minimum=1e-2,base=1):
        """converts num to (num1,num2) where num1*10**num2=num
    converts when not minimum<num<maximum.
    converts until base<num1<2*base"""
        pwr = 0
        while abs(num) > maximum or (abs(num)>2*base and pwr>0):
            pwr +=1
            num = num / 10
        while abs(num) < minimum or (abs(num)<base and pwr<0):
            pwr -=1
            num = num * 10
        return num,pwr
    def latexize(num,power=False,delim=','):
        if power:
            return ('%s \\cdot 10^{%d}' %(num,power)).replace('.',delim)
        else:
            return str(num).replace('.',delim)
    if __name__ == "__main__":
    #try:
        argc = len(sys.argv)
        var = 'Ooopsy-doopsy!'
        digitsAfter = 2
        typ = 10
        if argc >1:
            var = sub('[{}\. ]','',sys.argv[1])
            comment = '\\comments{%s}'%sys.argv[1]
            var = globals()[var]
        else:
            raise ValueError
        if argc >2:
            try:
                digitsAfter = int(sys.argv[2])
            except:
                typ = sys.argv[2]
        if argc >3:
            typ = sys.argv[2]
            digitsAfter = int(sys.argv[3])
        mini=1/10**digitsAfter
        if typ in ('int','i'):
            print comment,int(var)
        elif typ in ['float','f','nomath']:
            print comment + latexize (toStr (var, digitsAfter))
        else:
            strings = tenpower (var, minimum = mini)
            print comment + latexize (toStr (strings [0], digitsAfter), strings [1])
    #except Exception:
    # pass


    That is, typing "\ ptn {varAn1}" in LaTeX, substitute the value of the variable "varAn1" into the final document, if it is defined in "./path_to_your_scripts/script_name.py". And by writing "\ peval {1./5}" we get 0.2. Although I didn’t use this \ peval, so I didn’t finish it and it works lousy

    PS I need to process such a LaTeX file with the option “-shell-escape”

    Also popular now: