Bruce Jackson
Bruce Jackson

Reputation: 23

Python subprocess.call with variable substitution

The Code:

MOST_POPULAR_REPORTS_LOCATION = '/tmp'
MOST_POPULAR_REPORTS_FILE = 'filename.xml'
TEMP_DATA_FILE_LOCATION = '/tmp/other_location'
subprocess.call(["/bin/cp","-a","MOST_POPULAR_REPORTS_LOCATION MOST_POPULAR_REPORTS_FILE","TEMP_DATA_FILE_LOCATION"])

What do I put between MOST_POPULAR_REPORTS_LOCATION and MOST_POPULAR_REPORTS_FILE to put a / there? I have tried various combinations without success.

What I want is to separate the two variables with a /, so that it reads /tmp/filename.xml by using variable substitution. I do not want to hardcode the paths or filenames as they are used throughout the script.

Upvotes: 1

Views: 2564

Answers (1)

Lev Levitsky
Lev Levitsky

Reputation: 65791

Use os.path.join:

subprocess.call(["/bin/cp", "-a",
    os.path.join(MOST_POPULAR_REPORTS_LOCATION, MOST_POPULAR_REPORTS_FILE), 
        TEMP_DATA_FILE_LOCATION])

You should not put variable names in quotes, or you'll get string literals. This is not shell.

Upvotes: 1

Related Questions