Python Notes

The following are a few notes on the syntax, commands, etc. for python programming from the perspective of one fortran programmer. Assumes python version 3.x, which differs substantially from the 2.x versions.


python prog.py                   # Run python, where prog.py is a python program

python                           # Start python (or python3 for version 3.3)
>>> import numpy as np           # import package numpy
>>> print(np.sin(np.pi/4.))      # prints 0.7071067...; need np.sin as sin is not defined
>>> Ctl-D                        # quit

# To call a command from the OS:
from subprocess import call
call(["/bin/ls","-lt"])

# To call a command from the OS that uses pipes:
import subprocess
p1=subprocess.Popen(["/bin/ls"],stdout=subprocess.PIPE)   #first command
p2=subprocess.Popen(["/usr/bin/awk","END{print NR}"],stdin=p1.stdout,stdout=subprocess.PIPE) #pipe to second command
p1.stdout.close() #apparently so the order of finishing doesn't matter
output=p2.communicate()[0] #set the result from the pipe (a byte string) to 'output'
print(output.decode('ascii')) #print out this byte string as ascii

FORTRAN77/PYTHON TRANSLATION SYNTAX

write(6,'("Input temperature: ",$)')  #User I/O prompts
print("Input temperature: ",end="")

If num is an integer and var is a real,                         #Formatted print
write(6,'(f5.3,i3)') var,num
print("{0:5.3f} {1:3d}".format(var,num))  #the 0: is the first argument (var),
                                          #    1: is the second argument (num)


      character*80 name, oname
      write(6,'("Input filename: ",$)')
      read(5,*) name
      oname = "out_"//name
      write(6,'(a)') oname
      open(20,file=name)
      open(21,file=oname)
      do 100 i=1,5000
      read(20,*,end=120) var1, var2
      write(21,'(f9.4,1x,f9.4)') var1-var2,var1*var2
 100  continue
 120  stop
      end 
print('Input filename: ',end="")
name=input()                    # read name from terminal
oname="out_"+name               # make output filename
fin= open(name,'r')             # open input filename
fout= open(oname,'w')           # open output filename
for line in fin:                # loop until run out of lines
 line=line.strip()            # get rid of invisible characters like \n
 columns=line.split()         # split the fields of the line
 var1=float(columns[0])      # columns[1] and columns[2] are strings
 var2=float(columns[1])
 fout.write('{0:9.4f} {1:9.4f}\n'.format(var1-var2,var1*var2))