【问题标题】:How to pass arguments to python script similar to MATLAB function script?如何将参数传递给类似于 MATLAB 函数脚本的 python 脚本?
【发布时间】:2017-02-22 16:53:57
【问题描述】:

我有一个实现多个功能的 python 脚本,但我希望在每次使用哪些功能方面保持灵活。当我运行 Python 脚本时,我想传递一些参数,这些参数将作为“标志”来执行我的函数。

在 MATLAB 中看起来像这样:

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

我从命令窗口调用(例如):

metrics(1,0)

Python 我尝试使用

定义指标(最小值,最大值)

argparse()

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

有什么建议如何转置 Python Shell 中的 MATLAB 函数调用(我正在使用 Anaconda 的 Spyder)?

【问题讨论】:

  • 您想从命令行(如windows命令提示符或linux shell)还是从python shell调用函数?与 MATLAB 命令窗口等效的是 Python shell,而不是命令行。
  • @TheBlackCat Python shell,我的错。

标签: python matlab function


【解决方案1】:

您可以像在 MATLAB 中一样直接使用结果。参数解析的东西是用于从系统命令提示符或 shell 调用 python 脚本,而不是从 Python shell。所以有一个像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')

然后,从 python 或 ipython shell,执行:

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

虽然通常在 Python 中您会使用 TrueFalse。另外,我更改了参数名称,因为它们太容易与内置函数混淆,并且在 Python 中您不需要 == 1。此外,Python 支持默认参数,因此您可以执行以下操作:

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')

然后:

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

另外,Python 支持称为三元表达式的东西,基本上是if...else 表达式。所以这个:

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

可以写成:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 2015-05-13
    • 2016-09-02
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多