📜 ⬆️ ⬇️

Python in latex

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

There is a ready method in the form of a style file, 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 actually creates a jobname.py, writes output to jobname.py.out, jobname.py.err, and reads it.
The method is bad because the variables are not saved from the code to the code, and for this you have to use pickle, you have to re-import all the import, etc., every time, and it also seems to me that it is convenient to have all the calculations in one place in a separate file , so I built my amusement park ...

Everything is very simple. Add to the preamble the following:
  \ 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 concrete script with arguments, and the third can execute single-line Python code, which is then converted to a small sed `, to replace the dots with commas. And the last macro added that in order to display Python and the appearance of some errors in Latex, it was clear where the problem

In the script, I have a little trick for a beautiful conclusion (though only for the mathematical environment), and I can also share it with gray (naturally, sed will work only 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 


Ie typing in LaTeX "\ ptn {varAn1}", in the final document substitute the value of the variable "varAn1", 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 It is necessary to process such a LaTeX file with the "-shell-escape" option

Source: https://habr.com/ru/post/59782/


All Articles