Running SAS from Python on WRDS

Suppose I have a SAS macro that I call using a parameter, is there a way to pass that parameter from a Python program?

Turns out the answer is “yes!” Suppose I want SAS to operate on every daily TAQ file for 2006. It is easy to get Python to pull together a list of files, turn those into dates (extracted from the file names), and then pass these to SAS via the command line.

Here is SAS code using the variable &sysparm.

%put &sysparm;

Now here is some Python code that can be called as follows ./ 2006 to run the SAS code for each day in 2006.


# import the relevant modules
import glob
import re
import subprocess
import sys

# Extract the year from the command line
year = sys.argv[1]
print year

# Get the list of TAQ files for the given year
path = '/wrds/taq/sasdata/ct_' + str(year) + '*.sas7bdat'
print path
file_list = glob.glob(path)

# Now work through each file in the chosen year
for daily_file in file_list:
  # Use regular expression to extract the date; it's in YYYYMMDD format.
  date = re.sub('/wrds/taq/sasdata/ct_(\d{8}).sas7bdat', '\\1', daily_file)
  # Construct and run the necessary SAS command
  command = "time sas -log " + date + ".log "
  command += "-noterminal -sysparm \"" + date + "\""
  print command, shell=True)

print "All done!"
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s