Search code examples
pythonbashshellsubprocessopenfoam

Calling alias Command from python script


I need to run an OpenFOAM command by automatized python script.

My python code contains the lines

subprocess.Popen(['OF23'], shell=True)
subprocess.Popen(['for i in *; do surfaceConvert $i file_path/$i.stlb; done', shell=True)

where OF23 is a shell command is defined in alias as

alias OF23='export PATH=/usr/lib64/openmpi/bin/:$PATH;export LD_LIBRARY_PATH=/usr/lib64/openmpi/lib/:$LD_LIBRARY_PATH;source /opt/OpenFOAM/OpenFOAM-2.3.x/etc/bashrc'

This script runs the OpenFOAM command in terminal and the file_path defines the stl files which are converted to binary format

But when I run the script, I am getting 'OF23' is not defined.

How do I make my script to run the alias command and also perform the next OpenFOAM file conversion command


Solution

  • That's not going to work, even once you've resolved the alias problem. Each Python subprocess.Popen is run in a separate subshell, so the effects of executing OF23 won't persist to the second subprocess.Popen.

    Here's a brief demo:

    import subprocess
    
    subprocess.Popen('export ATEST="Hello";echo "1 $ATEST"', shell=True)
    subprocess.Popen('echo "2 $ATEST"', shell=True)
    

    output

    1 Hello
    2 
    

    So whether you use the alias, or just execute the aliased commands directly, you'll need to combine your commands into one subprocess.Popen call.

    Eg:

    subprocess.Popen('''export PATH=/usr/lib64/openmpi/bin/:$PATH;
    export LD_LIBRARY_PATH=/usr/lib64/openmpi/lib/:$LD_LIBRARY_PATH;
    source /opt/OpenFOAM/OpenFOAM-2.3.x/etc/bashrc;
    for i in *;
    do surfaceConvert $i file_path/$i.stlb;
    done''', shell=True)
    

    I've used a triple-quoted string so I can insert linebreaks, to make the shell commands easier to read.

    Obviously, I can't test that exact command sequence on my machine, but it should work.