ahmadkhalifa
ahmadkhalifa

Reputation: 55

Handling wildcard expansion with python subprocess call

I'm calling this function and using %s*silent to read files that have names with the following format: name.number.silent.

I get the name from start_model.split('/')[-1].split('.')[0] so don't worry about it.

This is obviously not working because these commands are actually never passed to the shell. If I were to use glob, how can I modify my code to do what I'm doing below?

from subprocess import call

def fragment_score(rosetta_path, silent_input_and_score_output, start_model):
    call([rosetta_path,
          '-mode score', 
          '-in::file::silent', '%s/%s*silent' % (silent_input_and_score_output, start_model.split('/')[-1].split('.')[0]),
          '-scorefile', '%s/scores1' % silent_input_and_score_output,
          '-n_matches', '50'])

Upvotes: 1

Views: 244

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295316

Use the Python glob module to generate a list of glob results, and splice it into your argument list at the same position where you would otherwise have a shell replacing a glob expression with the list of associated matches:

from subprocess import call
from glob import glob

def fragment_score(rosetta_path, silent_input_and_score_output, start_model):
    glob_exp = '%s/%s*silent' % (silent_input_and_score_output, start_model.split('/')[-1].split('.')[0])
    glob_results = glob(glob_exp)
    call([rosetta_path,
          '-mode score', 
          '-in::file::silent'
         ] + glob_results + [
          '-scorefile', '%s/scores1' % silent_input_and_score_output,
          '-n_matches', '50'])

In current Python 3.x, there's syntax that makes this a bit more natural:

    call([rosetta_path,
          '-mode score', 
          '-in::file::silent',
          *glob_results,
          '-scorefile', '%s/scores1' % silent_input_and_score_output,
          '-n_matches', '50'])

Upvotes: 1

Related Questions