0

I have a python script that implements several functions, but I want to be flexible in terms of which functions I use every time. When I would run the Python Script I would want to pass some arguments that would stand as "flags" for executing my functions.

In MATLAB would look something like this:

function metrics( Min, Max )
%UNTITLED Summary of this function goes here
%   Detailed explanation goes here
x = [1,2,3,4,5,5];

if (Min==1)
    min(x)
else
    disp('something')
end

if (Max==1)
    max(x)
else
    disp('else')
end

end

Which I call from command window with (for example):

metrics(1,0)

In Python I tried using

def metrics(min, max)

argparse()

and

os.system("metrics.py 1,1")

Any suggestion how to transpose the MATLAB function calling in the Python Shell (I am using Anaconda's Spyder for the matter)?

Community
  • 1
  • 1
RMS
  • 1,350
  • 5
  • 18
  • 35
  • Do you want to call functions from the command line (such as the windows command prompt or linux shell) or from the python shell? The equivalent of the MATLAB command window is the Python shell, not the command line. – TheBlackCat Oct 13 '16 at 14:20
  • @TheBlackCat the Python shell, my bad. – RMS Oct 13 '16 at 14:21

1 Answers1

3

You can use the results directly just like you do in MATLAB. The argument parsing stuff is for calling python scripts from the system command prompt or shell, not from the Python shell. So have a script file like myscript.py:

def metrics(minval, maxval):
    """UNTITLED Summary of this function goes here

    Detailed explanation goes here.
    """
    x = [1, 2, 3, 4, 5, 5]

    if minval:
        print(min(x))
    else:
        print('something')

    if maxval:
        print(max(x))
    else:
        print('else')

Then, from the python or ipython shell, do:

>>> from myscript import metrics
>>> metrics(1, 0)

Although typically in Python you would use True and False. Also, I changed the argument names since they are too easy to confuse with builtins, and in Python you don't need the == 1. Also, Python supports default arguments, so you could do something like this:

def metrics(minval=False, maxval=False):
    """UNTITLED Summary of this function goes here

    Detailed explanation goes here.
    """
    x = [1, 2, 3, 4, 5, 5]

    if minval:
        print(min(x))
    else:
        print('something')

    if maxval:
        print(max(x))
    else:
        print('else')

then:

>>> from myscript import metrics
>>> matrics(True)
>>> metrics(maxval=True)

Also, Python supports something called ternary expressions, which are basically if...else expressions. So this:

    if maxval:
        print(max(x))
    else:
        print('else')

Could be written as:

    print(max(x) if maxval else 'else')
TheBlackCat
  • 9,791
  • 3
  • 24
  • 31