Hello Everyone,
I am trying to add a dynamic feature to the topic of Passing-Parameters-from-SAS-to-Python-Script
Therefore, I wanted to use a SAS macro as a wrapper around the python code, that @HarrySnart used.
%macro print_macval_not_working(p_macvarname=);
%let myvar="&p_macvarname.";
%PUT &=myvar;
proc python;
submit;
x = SAS.symget('myvar')
print('macro variable myvar = ' + x)
py_var = 'Inside python'
SAS.symput('macrovar', py_var)
endsubmit;
run;
%put &=macrovar;
%put &=myvar;
%mend;
%print_macval_not_working(p_macvarname=test);
However, I get this ERROR message, which I would like to understand:
ERROR: Submit block cannot be directly placed in a macro. Instead, place the submit block into a file first and then use %include
to include the file within a macro definition.
ERROR: Submit code parse failure.
ERROR 180-322: Statement is not valid or it is used out of proper order.
Why is it just with the PROC PYTHON Procedure not possible to use a macro?
When I just create a simple macro without the python procedure, it works fine:
%macro print_macval_works(p_macvarname=);
%let myvar="&p_macvarname.";
%PUT &=myvar;
%mend;
%print_macval_works(p_macvarname=ibson);
What are the "special circumstances" that prevent the macro "print_macval_not_working" from working?
Python code depends on the layout to separate statements and identify blocks (through indentation).
Since a macro is tokenized upon compilation, this layout is lost and the Python code would become unusable. The %INCLUDE, OTOH, is executed when the macro executes, and will therefore result in the code being inserted as it is in the file, with the layout intact
This is the same reason that also prohibits use of DATALINES in a macro.
Python code depends on the layout to separate statements and identify blocks (through indentation).
Since a macro is tokenized upon compilation, this layout is lost and the Python code would become unusable. The %INCLUDE, OTOH, is executed when the macro executes, and will therefore result in the code being inserted as it is in the file, with the layout intact
This is the same reason that also prohibits use of DATALINES in a macro.
I'm just guessing, but PYTHON cares about leading white space (indenting) in code. When you compile a macro, it does not preserve white space in the code it will generate when executed. So likely a compiled macro can't generate valid python code, if the python code is inline in the macro definition. It's the same reason you can't use a CARDS statement inside a macro. The %include approach kindly recommended in the error message sounds like a good workaround.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.