Field Precision title

Processing all Mesh files in a directory with Python

In recent test of Pulse (our program for magnetic field diffusion), we decided to run all the examples included with the program package. The first step for each example is to generate a Mesh output file for input to Pulse. As an alternative to interactively processing each by hand, I decided to make a Python utility to do the work automatically. The resulting script is not limited to Mesh — it can be adapted to any program that can run from the command prompt.

There are many options to find out how to do new things in Python and to refresh your memory on old things. I found the quickest route is to use an Internet search engine. For this project I used topics like python all files in directory and python remove file suffix. Here's the resulting script

# File makemesh.pyw
# Process files *.min in the current directory with mesh.exe
1. import subprocess, os, glob
2. ProgName = "c:\\fieldp\\tricomp\\mesh64 "
3. for infile in glob.glob('*.min'):
4. FilePrefix =os.path.splitext(os.path.basename(infile))[0]
5. Command = ProgName + FilePrefix
6. print("Processing: " + infile)
7. subprocess.Popen(Command)

Line 1 imports the required modules. Note the double backslashes in Line 2 to enter the backslash character in the string. Line 3 stores all file names that match the pattern for Mesh input files. Line 4 extracts the current file prefix, while Line 7 runs Mesh.

You can run the script by moving it into the directory that contains the MIN files and then double-clicking on it in your file manager. I use a different approach. I have set a directory c:\batch on the Windows path that I use for command-line utilities. I copied makemesh.pyw to the directory and wrote the file makemesh.bat with the content:

python c:\batch\makemesh.pyw

In this case, I can open a terminal in any directory and simply type makemesh.

In the script, note that the .wait() option does not appear at the end of subprocess.Popen. This is because the mesh generation operations are independent and may run in parallel (multiple threads). This approach saves time if you have a multi-core computer. On the other hand, you should be careful running multiple programs where one program may use data generated by another. For instance, this example illustrates how to both process the meshes and to generate Pulse solutions:

import subprocess, os, glob
MeshProgName = "c:\\fieldp\\tricomp\\mesh64 "
PulseProgName = "c:\\fieldp\\tricomp\\pulse64 "
for infile in glob.glob('*.min'):
  FilePrefix =os.path.splitext(os.path.basename(infile))[0]
  print("Creating mesh: " + infile)
  Command = MeshProgName + FilePrefix
  subprocess.Popen(Command).wait()
  print("Creating solution: " + infile)
  Command = PulseProgName + FilePrefix
  subprocess.Popen(Command).wait()

LINKS