Line magics are only supported by the IPython command line. They cannot simply be used inside a script, because %something is not correct Python syntax.
If you want to do this from a script you have to get access to the IPython API and then call the run_line_magic function.
Instead of %matplotlib inline, you will have to do something like this in your script:
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
A similar approach is described in this answer, but it uses the deprecated magic function.
Note that the script still needs to run in IPython. Under vanilla Python the get_ipython function returns None and get_ipython().run_line_magic will raise an AttributeError.