Skip to content

Instantly share code, notes, and snippets.

@ClePol
Created June 5, 2020 12:35
Show Gist options
  • Save ClePol/171f4717613bf0db483d80239b6ec9ac to your computer and use it in GitHub Desktop.
Save ClePol/171f4717613bf0db483d80239b6ec9ac to your computer and use it in GitHub Desktop.
How to run freesurfer inside a python script
import shlex
import subprocess
import sys
def which(program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
if is_exe(os.path.join(os.getenv('FREESURFER_HOME'),'bin',program)):
return os.path.join(os.getenv('FREESURFER_HOME'),'bin',program)
if is_exe(os.path.join('.',program)):
return os.path.join('.',program)
return None
def run_cmd(cmd,err_msg):
"""
execute the comand
"""
clist = cmd.split()
progname=which(clist[0])
if (progname) is None:
print('ERROR: '+ clist[0] +' not found in path!')
sys.exit(1)
clist[0]=progname
cmd = ' '.join(clist)
print('#@# Command: ' + cmd+'\n')
args = shlex.split(cmd)
process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if stderr != b'':
print('ERROR: '+ err_msg)
return stdout
cmd = 'mri_seghead --invol ' + PATH_TO_IMAGE + ' --fill 255 --thresh 30 --nhitsmin 2 --dilate 5'
fs_output = run_cmd(cmd,"Failed to run mri_seghead")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment