Skip to content

API Reference

Oct2Py

oct2py.Oct2Py

Manages an Octave session.

Uses MAT files to pass data between Octave and Numpy. The function must either exist as an m-file in this directory or on Octave's path. The first command will take about 0.5s for Octave to load up. The subsequent commands will be much faster.

You may provide a logger object for logging events, or the oct2py.get_log() default will be used. When calling commands, logger.info() will be used to stream output, unless a stream_handler is provided.

Parameters:

Name Type Description Default
settings Oct2PySettings

Settings object supplying defaults for all other parameters. When omitted, a default Oct2PySettings() is created (which reads OCT2PY_* environment variables automatically). Explicit keyword arguments always override values from settings.

None
logger logging object

Optional logger to use for Oct2Py session

None
timeout float

Timeout in seconds for commands

None
oned_as (row, column)

If 'column', write 1-D numpy arrays as column vectors. If 'row', write 1-D numpy arrays as row vectors.}

'row'
temp_dir str

If specified, the session's MAT files will be created in the directory, otherwise a default directory is used. On Linux, /dev/shm (a RAM-based tmpfs) is used automatically when available, which significantly reduces per-call overhead. On other platforms you can point this at a tmpfs mount for the same benefit.

None
convert_to_float bool

If true, convert integer types to float when passing to Octave.

None
backend

The graphics_toolkit to use for plotting. Use "disable" to suppress all figure rendering (useful in headless or computation-only environments where a display is unavailable).

None
keep_matlab_shapes

If true, matlab shapes will be preserved (scalars as (1,1) etc)

None
auto_show bool

If True, automatically capture open Octave figures after each call and display them via matplotlib. Defaults to True when the PYCHARM_HOSTED environment variable is set (i.e. when running inside PyCharm), False otherwise. Set explicitly to override.

None
extra_cli_options str

Extra command-line options appended to the Octave invocation.

None
executable str

Path to the Octave executable. Resolved in order: this argument, OCTAVE_EXECUTABLE env var, octave/octave-cli on PATH, then Flatpak.

None
load_octaverc bool

If True (default), source ~/.octaverc during startup. Set to False to skip loading the user init file, which is useful in reproducible or sandboxed environments where the init file may alter the path, set conflicting options, or is simply unavailable.

None
plot_format str

Default format for saved plots (default "svg").

None
plot_name str

Default base name for saved plots (default "plot").

None
plot_width int

Default plot width in pixels.

None
plot_height int

Default plot height in pixels.

None
plot_res int

Default plot resolution in pixels per inch.

None
ramdisk_size_mb int

macOS only. When set to a positive integer, oct2py will create a temporary HFS+ RAM disk of the given size (in MiB) and use it as the MAT-file exchange directory. The disk is unmounted automatically on session exit. Has no effect on Linux (where /dev/shm is used automatically) or on Windows. Defaults to 0 (disabled).

None
Source code in oct2py/core.py
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
class Oct2Py:
    """Manages an Octave session.

    Uses MAT files to pass data between Octave and Numpy.
    The function must either exist as an m-file in this directory or
    on Octave's path.
    The first command will take about 0.5s for Octave to load up.
    The subsequent commands will be much faster.

    You may provide a logger object for logging events, or the oct2py.get_log()
    default will be used.  When calling commands, logger.info() will be used
    to stream output, unless a `stream_handler` is provided.

    Parameters
    ----------
    settings : Oct2PySettings, optional
        Settings object supplying defaults for all other parameters.
        When omitted, a default ``Oct2PySettings()`` is created (which
        reads ``OCT2PY_*`` environment variables automatically).
        Explicit keyword arguments always override values from settings.
    logger : logging object, optional
        Optional logger to use for Oct2Py session
    timeout : float, optional
        Timeout in seconds for commands
    oned_as : {'row', 'column'}, optional
        If 'column', write 1-D numpy arrays as column vectors.
        If 'row', write 1-D numpy arrays as row vectors.}
    temp_dir : str, optional
        If specified, the session's MAT files will be created in the
        directory, otherwise a default directory is used.  On Linux,
        ``/dev/shm`` (a RAM-based tmpfs) is used automatically when
        available, which significantly reduces per-call overhead.  On
        other platforms you can point this at a tmpfs mount for the
        same benefit.
    convert_to_float : bool, optional
        If true, convert integer types to float when passing to Octave.
    backend: string, optional
        The graphics_toolkit to use for plotting.  Use ``"disable"`` to
        suppress all figure rendering (useful in headless or
        computation-only environments where a display is unavailable).
    keep_matlab_shapes: bool, optional
        If true, matlab shapes will be preserved (scalars as (1,1) etc)
    auto_show : bool, optional
        If True, automatically capture open Octave figures after each call
        and display them via matplotlib.  Defaults to True when the
        ``PYCHARM_HOSTED`` environment variable is set (i.e. when running
        inside PyCharm), False otherwise.  Set explicitly to override.
    extra_cli_options : str, optional
        Extra command-line options appended to the Octave invocation.
    executable : str, optional
        Path to the Octave executable. Resolved in order: this argument,
        ``OCTAVE_EXECUTABLE`` env var, ``octave``/``octave-cli`` on
        ``PATH``, then Flatpak.
    load_octaverc : bool, optional
        If True (default), source ``~/.octaverc`` during startup.  Set to
        False to skip loading the user init file, which is useful in
        reproducible or sandboxed environments where the init file may
        alter the path, set conflicting options, or is simply unavailable.
    plot_format : str, optional
        Default format for saved plots (default ``"svg"``).
    plot_name : str, optional
        Default base name for saved plots (default ``"plot"``).
    plot_width : int, optional
        Default plot width in pixels.
    plot_height : int, optional
        Default plot height in pixels.
    plot_res : int, optional
        Default plot resolution in pixels per inch.
    ramdisk_size_mb : int, optional
        macOS only.  When set to a positive integer, oct2py will create
        a temporary HFS+ RAM disk of the given size (in MiB) and use it
        as the MAT-file exchange directory.  The disk is unmounted
        automatically on session exit.  Has no effect on Linux (where
        ``/dev/shm`` is used automatically) or on Windows.  Defaults to
        ``0`` (disabled).
    """

    def __init__(  # noqa
        self,
        settings=None,
        logger=None,
        timeout=None,
        oned_as=None,
        temp_dir=None,
        convert_to_float=None,
        backend=None,
        keep_matlab_shapes=None,
        auto_show=None,
        extra_cli_options=None,
        executable=None,
        load_octaverc=None,
        plot_format=None,
        plot_name=None,
        plot_width=None,
        plot_height=None,
        plot_res=None,
        ramdisk_size_mb=None,
    ):
        if settings is None:
            settings = Oct2PySettings()
        # Apply any explicit kwargs as overrides on top of the settings object.
        _locals = locals()
        _overrides = {
            f: _locals[f]
            for f in Oct2PySettings.model_fields
            if f != "auto_show" and _locals.get(f) is not None
        }
        # Resolve auto_show: explicit kwarg > settings > env detection.
        _auto_show = auto_show if auto_show is not None else settings.auto_show
        if _auto_show is None:
            _auto_show = bool(os.environ.get("PYCHARM_HOSTED"))
            if _overrides.get("backend", settings.backend) == "disable":
                _auto_show = False
        self._settings = settings.model_copy(update={**_overrides, "auto_show": _auto_show})
        self._engine = None
        self._logger = None
        self.logger = logger
        self._temp_dir_owner = False
        self._ramdisk_device = None
        self._out_fh = None
        self._user_classes = {}
        self._function_ptrs = {}
        _instances.add(self)
        self.restart()

    @property
    def logger(self):
        """The logging instance used by the session."""
        return self._logger

    @logger.setter
    def logger(self, value):
        self._logger = value or get_log()
        if self._engine:
            self._engine.logger = self._logger

    @property
    def settings(self):
        """The session's current settings."""
        return self._settings

    @settings.setter
    def settings(self, value):
        self._settings = value

    def __enter__(self):
        """Return octave object, restart session if necessary"""
        if not self._engine:
            self.restart()
        return self

    def __exit__(self, type_, value, traceback):
        """Close session"""
        self.exit()

    def __del__(self):
        """Delete session"""
        try:  # noqa: SIM105
            self.exit()
        except Exception:  # noqa: S110  # pragma: no cover
            pass

    def exit(self):
        """Quits this octave session and cleans up."""
        if self._engine:
            if callable(atexit.unregister):
                atexit.unregister(self._engine._cleanup)
            self._engine.repl.terminate()
        self._engine = None
        if self._out_fh and not self._out_fh.closed:
            atexit.unregister(self._out_fh.close)
            self._out_fh.close()
            self._out_fh = None
        if self._temp_dir_owner and self._settings.temp_dir and osp.isdir(self._settings.temp_dir):
            shutil.rmtree(self._settings.temp_dir, ignore_errors=True)
            self._settings.temp_dir = None
            self._temp_dir_owner = False
        if self._ramdisk_device:
            _detach_macos_ramdisk(self._ramdisk_device)
            self._ramdisk_device = None

    def push(self, name, var, timeout=None, verbose=True):
        """
        Put a variable or variables into the Octave session.

        Parameters
        ----------
        name : str or list
            Name of the variable(s).
        var : object or list
            The value(s) to pass.
        timeout : float
            Time to wait for response from Octave (per line).
        verbose: bool
             Log Octave output at INFO level.  If False, log at DEBUG level.

        Examples
        --------
        >>> from oct2py import octave
        >>> y = [1, 2]
        >>> octave.push('y', y)
        >>> octave.pull('y')
        array([[1., 2.]])
        >>> octave.push(['x', 'y'], ['spam', [1, 2, 3, 4]])
        >>> octave.pull(['x', 'y'])  # doctest: +SKIP
        [u'spam', array([[1, 2, 3, 4]])]

        Notes
        -----
        Integer type arguments will be converted to floating point
        unless `convert_to_float=False`.

        """
        timeout = timeout if timeout is not None else self._settings.timeout
        if isinstance(name, str):
            name = [name]
            var = [var]

        for n, v in zip(name, var, strict=False):
            self.feval("assignin", "base", n, v, nout=0, timeout=timeout, verbose=verbose)

    def pull(self, var, timeout=None, verbose=True):
        """
        Retrieve a value or values from the Octave session.

        Parameters
        ----------
        var : str or list
            Name of the variable(s) to retrieve.
        timeout : float, optional.
            Time to wait for response from Octave (per line).
        verbose: bool
             Log Octave output at INFO level.  If False, log at DEBUG level.

        Returns
        -------
        out : object
            Object returned by Octave.

        Raises
        ------
        Oct2PyError
            If the variable does not exist in the Octave session.

        Examples
        --------
          >>> from oct2py import octave
          >>> y = [1, 2]
          >>> octave.push('y', y)
          >>> octave.pull('y')
          array([[1., 2.]])
          >>> octave.push(['x', 'y'], ['spam', [1, 2, 3, 4]])
          >>> octave.pull(['x', 'y'])  # doctest: +SKIP
          [u'spam', array([[1, 2, 3, 4]])]

        """
        timeout = timeout if timeout is not None else self._settings.timeout
        if isinstance(var, str):
            var = [var]
        outputs = []
        for name in var:
            exist = self._exist(name)
            if exist == 1:
                outputs.append(self.feval("evalin", "base", name, timeout=timeout, verbose=verbose))
            else:
                outputs.append(self.get_pointer(name, timeout=timeout))

        if len(outputs) == 1:
            return outputs[0]
        return outputs

    def get_pointer(self, name, timeout=None, expr=False):
        """Get a pointer to a named object in the Octave workspace.

        Parameters
        ----------
        name: str
            The name of the object in the Octave workspace, or an Octave
            expression string when ``expr=True``.
        timeout: float, optional.
            Time to wait for response from Octave (per line).
        expr: bool, optional (default False)
            If True, treat `name` as an Octave expression string rather than a
            variable name. The expression is assigned to a unique temporary
            variable in the Octave workspace and a pointer to that variable is
            returned. Use this when you need to pass an expression that cannot
            be converted to a Python object (e.g. cell arrays of function
            handles like ``{@cos @sin}``).

            Note: the temporary variable persists in the Octave workspace for
            the lifetime of the session.

        Examples
        --------
        >>> from oct2py import octave
        >>> octave.eval('foo = [1, 2];')
        >>> ptr = octave.get_pointer('foo')
        >>> ptr.value
        array([[1., 2.]])
        >>> ptr.address
        'foo'
        >>> # Can be passed as an argument
        >>> octave.disp(ptr)  # doctest: +SKIP
        1  2

        >>> from oct2py import octave
        >>> sin = octave.get_pointer('sin')  # equivalent to `octave.sin`
        >>> sin.address
        '@sin'
        >>> x = octave.quad(sin, 0, octave.pi())
        >>> x
        2.0

        >>> from oct2py import octave
        >>> ptr = octave.get_pointer('{@cos @sin}', expr=True)
        >>> type(ptr).__name__
        'OctaveVariablePtr'
        >>> # Pass the cell of function handles to an Octave function
        >>> octave.feval('cellfun', '@(f) f(0)', ptr)  # doctest: +SKIP

        Notes
        -----
        Pointers can be passed to `feval` or dynamic functions as function
        arguments.  A pointer passed as a nested value will be passed by value
        instead.

        Raises
        ------
        Oct2PyError
            If the variable does not exist in the Octave session or is of
            unknown type.

        Returns
        -------
        A variable, object, user class, or function pointer as appropriate.
        """
        timeout = timeout if timeout is not None else self._settings.timeout
        if expr:
            tmp_name = f"_oct2py_expr_{uuid.uuid4().hex}"
            self.eval(f"{tmp_name} = {name}", timeout=timeout)
            return _make_variable_ptr_instance(self, tmp_name)

        exist = self._exist(name)
        isobject = self._isobject(name, exist)

        if exist == 0:
            raise Oct2PyError('"%s" is undefined' % name)

        elif exist == 1:
            return _make_variable_ptr_instance(self, name)

        elif isobject:
            return self._get_user_class(name)

        elif exist in [2, 3, 5]:
            return self._get_function_ptr(name)

        raise Oct2PyError('Unknown type for object "%s"' % name)

    def extract_figures(self, plot_dir, remove=False):
        """Extract the figures in the directory to IPython display objects.

        Parameters
        ----------
        plot_dir: str
            The plot dir where the figures were created.
        remove: bool, optional.
            Whether to remove the plot directory after saving.

        Returns
        -------
        The list of figure objects.
        """
        if not self._engine:
            msg = "Session is not open"
            raise Oct2PyError(msg)
        figures = self._engine.extract_figures(plot_dir, remove)
        return figures

    def show(self):
        """Render open Octave figures and display them using matplotlib.

        Captures all currently open Octave figure windows as PNG images and
        displays them via :func:`matplotlib.pyplot.imshow`.  This is useful
        in environments such as PyCharm that can display matplotlib figures
        inline but cannot show Octave's native figure windows.

        Requires ``matplotlib`` to be installed.  If it is not available,
        the method returns silently.

        This is called automatically after each eval/feval when
        ``auto_show=True`` (which is the default inside PyCharm).

        Examples
        --------
        >>> import oct2py  # doctest: +SKIP
        >>> oc = oct2py.Oct2Py()  # doctest: +SKIP
        >>> _ = oc.plot([1, 2, 3])  # doctest: +SKIP
        >>> oc.show()  # displays the Octave figure inline  # doctest: +SKIP
        """
        self._show_figures()

    def _show_figures(self):
        """Capture open Octave figures and display them via matplotlib."""
        if not self._engine:
            return
        if self._settings.backend == "disable":
            return
        try:
            import matplotlib.image as mpimg  # noqa: PLC0415
            import matplotlib.pyplot as plt  # noqa: PLC0415
        except ImportError:  # pragma: no cover
            return

        plot_dir = tempfile.mkdtemp(dir=self._settings.temp_dir)
        try:
            # Temporarily switch to inline mode so _make_figures uses a
            # headless-compatible toolkit (gnuplot/qt offscreen) rather than
            # the default interactive toolkit, which requires a display.
            saved = self._engine.plot_settings.copy()
            self._engine.plot_settings = {**saved, "backend": "inline"}
            try:
                self._engine.make_figures(plot_dir)
            finally:
                self._engine.plot_settings = saved

            figure_files = sorted(glob.glob(osp.join(plot_dir, "*")))
            for img_path in figure_files:
                img = mpimg.imread(img_path)
                _, ax = plt.subplots()
                ax.imshow(img)
                ax.axis("off")
            if figure_files:
                plt.show()
        finally:
            shutil.rmtree(plot_dir, ignore_errors=True)

    def feval(self, func_path, *func_args, **kwargs):
        """Run a function in Octave and return the result.

        Parameters
        ----------
        func_path : str
            Name of function to run or a path to an m-file.
        func_args : object, optional
            Args to send to the function.

        Other Parameters
        ----------------
        nout : int or str, optional
            The desired number of returned values, defaults to 1. If nout
            value is 'max_nout', _get_max_nout() will be used.
        quiet : bool, optional
            If True, execute the function but do not capture or return any
            output.  Takes precedence over ``nout``.
        store_as : str, optional
            If given, saves the result to the given Octave variable name
            instead of returning it.
        verbose : bool, optional
            Log Octave output at INFO level.  If False, log at DEBUG level.
        stream_handler : callable, optional
            A function that is called for each line of output from the
            evaluation.
        timeout : float, optional
            The timeout in seconds for the call.
        plot_dir : str, optional
            If specified, save the session's plot figures to the plot
            directory instead of displaying the plot window.
        plot_backend : str, optional
            The plotting back end to use.
        plot_name : str, optional
            Saved plots will start with `plot_name` and
            end with "_%%.xxx' where %% is the plot number and
            xxx is the `plot_format`.
        plot_format : str, optional
            The format in which to save the plot.
        plot_width : int, optional
            The plot width in pixels.
        plot_height : int, optional
            The plot height in pixels.

        Notes
        -----
        The function arguments passed follow Octave calling convention, not
        Python. That is, all values must be passed as a comma separated list,
        not using `x=foo` assignment.

        **Plot rendering limitation (issue #172):** oct2py executes Octave
        synchronously, so figure updates triggered by ``pause()`` calls inside
        a ``.m`` function are not rendered mid-execution — plots are only
        exposed after the entire function returns.  For interactive display
        this means figures appear at the end of the call, not incrementally.
        To capture figures from inside a ``.m`` file programmatically, pass
        ``plot_dir`` and then call :meth:`extract_figures`::

            plot_dir = tempfile.mkdtemp()
            octave.feval("my_func.m", plot_dir=plot_dir)
            imgs = octave.extract_figures(plot_dir)

        Examples
        --------
        >>> from oct2py import octave
        >>> cell = octave.feval('cell', 10, 10, 10)
        >>> cell.shape
        (10, 10, 10)

        >>> from oct2py import octave
        >>> x = octave.feval('linspace', 0, octave.pi() / 2)
        >>> x.shape
        (1, 100)

        >>> from oct2py import octave
        >>> x = octave.feval('svd', octave.hilb(3))
        >>> x
        array([[1.40831893],
               [0.12232707],
               [0.00268734]])
        >>> # specify three return values
        >>> (u, v, d) = octave.feval('svd', octave.hilb(3), nout=3)
        >>> u.shape
        (3, 3)

        Returns
        -------
        The Python value(s) returned by the Octave function call.
        """  # noqa: DOC102, DOC103
        if not self._engine:
            msg = "Session is not open"
            raise Oct2PyError(msg)

        # nout handler
        nout = kwargs.get("nout")
        if kwargs.get("quiet"):
            nout = -1
        elif nout is None:
            nout = 1
        elif nout == "max_nout":
            nout = self._get_max_nout(func_path)

        plot_dir = kwargs.get("plot_dir")

        # Choose appropriate plot backend.
        default_backend = "inline" if plot_dir else self._settings.backend
        backend = kwargs.get("plot_backend", default_backend)
        # Map "disable" to "inline" so octave_kernel sets defaultfigurevisible=off.
        if backend == "disable":
            backend = "inline"

        settings = dict(
            backend=backend,
            format=kwargs.get("plot_format"),
            name=kwargs.get("plot_name"),
            width=kwargs.get("plot_width"),
            height=kwargs.get("plot_height"),
            resolution=kwargs.get("plot_res"),
        )
        self._engine.plot_settings = settings

        _is_dotted_name = kwargs.pop("_is_dotted_name", False)
        if _is_dotted_name:
            func_name = func_path
            dname = ""
        else:
            dname = osp.dirname(func_path)
            fname = osp.basename(func_path)
            func_name, ext = osp.splitext(fname)
            if ext and ext != ".m":
                msg = "Need to give path to .m file"
                raise TypeError(msg)

        if func_name == "clear":
            msg = 'Cannot use `clear` command directly, use eval("clear(var1, var2)")'
            raise Oct2PyError(msg)

        stream_handler = kwargs.get("stream_handler")
        verbose = kwargs.get("verbose", True)
        store_as = kwargs.get("store_as", "")
        _t = kwargs.get("timeout")
        timeout = _t if _t is not None else self._settings.timeout
        if not stream_handler:
            stream_handler = self.logger.info if verbose else self.logger.debug

        return self._feval(
            func_name,
            func_args,
            dname=dname,
            nout=nout,
            timeout=timeout,
            stream_handler=stream_handler,
            store_as=store_as,
            plot_dir=plot_dir,
        )

    def eval(  # noqa: PLR0913
        self,
        cmds,
        verbose=True,
        timeout=None,
        stream_handler=None,
        temp_dir=None,
        plot_dir=None,
        plot_name=None,
        plot_format=None,
        plot_backend=None,
        plot_width=None,
        plot_height=None,
        plot_res=None,
        nout=0,
        quiet=False,
        **kwargs,
    ):
        """Evaluate an Octave command or commands.

        Parameters
        ----------
        cmds : str or list
            Commands(s) to pass to Octave.
        verbose : bool, optional
             Log Octave output at INFO level.  If False, log at DEBUG level.
        stream_handler: callable, optional
            A function that is called for each line of output from the
            evaluation.
        timeout : float, optional
            Time to wait for response from Octave (per line).  If not given,
            the instance `timeout` is used.
        nout : int or str, optional.
            The desired number of returned values, defaults to 0.  If nout
            is 0, the `ans` will be returned as the return value. If nout
            value is 'max_nout', _get_max_nout() will be used.
        quiet : bool, optional
            If True, execute the command(s) but do not capture or return any
            output.  Useful when ``ans`` is not serialisable, or to avoid
            double-printing in Jupyter.  Takes precedence over ``nout``.
        temp_dir: str, optional
            If specified, the session's MAT files will be created in the
            directory, otherwise a the instance `temp_dir` is used.
            a shared memory (tmpfs) path.
        plot_dir: str, optional
            If specified, save the session's plot figures to the plot
            directory instead of displaying the plot window.
        plot_name : str, optional
            Saved plots will start with `plot_name` and
            end with "_%%.xxx' where %% is the plot number and
            xxx is the `plot_format`.
        plot_format: str, optional
            The format in which to save the plot (PNG by default).
        plot_width: int, optional
            The plot with in pixels.
        plot_height: int, optional
            The plot height in pixels.
        plot_backend: str, optional
            The plot backend to use.
        plot_res: int, optional
            The plot resolution in pixels per inch.
        **kwargs Deprecated kwargs.

        Examples
        --------
        >>> from oct2py import octave
        >>> octave.eval('disp("hello")') # doctest: +SKIP
        hello
        >>> x = octave.eval('round(quad(@sin, 0, pi/2));')
        >>> x
        1.0

        >>> a = octave.eval('disp("hello");1;')  # doctest: +SKIP
        hello
        >>> a = octave.eval('disp("hello");1;', verbose=False)
        >>> a
        1.0

        >>> from oct2py import octave
        >>> lines = []
        >>> octave.eval('for i = 1:3; disp(i);end', \
                        stream_handler=lines.append)
        >>> lines  # doctest: +SKIP
        [' 1', ' 2', ' 3']

        Returns
        -------
        out : object
            Octave "ans" variable, or None.

        Notes
        -----
        The deprecated `log` kwarg will temporarily set the `logger` level to
        `WARN`.  Using the `logger` settings directly is preferred.
        The deprecated `return_both` kwarg will still work, but the preferred
        method is to use the `stream_handler`.  If `stream_handler` is given,
        the `return_both` kwarg will be honored but will give an empty string
        as the response.

        Raises
        ------
        Oct2PyError
            If the command(s) fail.
        """  # noqa: DOC103
        if isinstance(cmds, str):
            cmds = [cmds]

        timeout = timeout if timeout is not None else self._settings.timeout
        plot_name = plot_name if plot_name is not None else self._settings.plot_name
        plot_format = plot_format if plot_format is not None else self._settings.plot_format
        plot_width = plot_width if plot_width is not None else self._settings.plot_width
        plot_height = plot_height if plot_height is not None else self._settings.plot_height
        plot_res = plot_res if plot_res is not None else self._settings.plot_res

        prev_temp_dir = self._settings.temp_dir
        self._settings.temp_dir = temp_dir or self._settings.temp_dir
        prev_log_level = self.logger.level

        if kwargs.get("log") is False:
            self.logger.setLevel(logging.WARN)

        for name in ["log", "return_both"]:
            if name not in kwargs:
                continue
            msg = "Using deprecated `%s` kwarg, see docs on `Oct2Py.eval()`"
            warnings.warn(msg % name, Oct2PyWarning, stacklevel=2)

        return_both = kwargs.pop("return_both", False)
        lines: list[str] = []
        if return_both and not stream_handler:
            stream_handler = lines.append

        ans = None
        for cmd in cmds:
            resp = self.feval(
                "evalin",
                "base",
                cmd,
                nout=nout,
                quiet=quiet,
                timeout=timeout,
                stream_handler=stream_handler,
                verbose=verbose,
                plot_dir=plot_dir,
                plot_name=plot_name,
                plot_format=plot_format,
                plot_backend=plot_backend,
                plot_width=plot_width,
                plot_height=plot_height,
                plot_res=plot_res,
            )
            if resp is not None:
                ans = resp

        self._settings.temp_dir = prev_temp_dir
        self.logger.setLevel(prev_log_level)

        if return_both:
            return "\n".join(lines), ans
        return ans

    def run(self, script, **kwargs):
        """Run an Octave script file in the base workspace.

        Unlike calling ``octave.run(script)`` via dynamic dispatch (which runs
        the script inside a temporary function scope and discards any variables
        it creates), this method executes the script through ``evalin('base',
        ...)``, so variables assigned by the script persist in the Octave base
        workspace and can be retrieved with :meth:`pull`.

        Parameters
        ----------
        script : str
            Name of the script or path to an ``.m`` file, passed directly to
            Octave's ``run()`` built-in.
        **kwargs
            Additional keyword arguments forwarded to :meth:`eval` (e.g.
            ``verbose``, ``timeout``, ``stream_handler``).

        Examples
        --------
        >>> import os, tempfile
        >>> from oct2py import Oct2Py
        >>> oc = Oct2Py()
        >>> with tempfile.NamedTemporaryFile(suffix='.m', mode='w', delete=False) as f:
        ...     _ = f.write('b = 42;')
        ...     script_path = f.name
        >>> oc.run(script_path)
        >>> oc.pull('b')
        42.0
        >>> oc.exit()
        >>> os.unlink(script_path)
        """
        # Escape backslashes and single quotes so the path is safe inside
        # an Octave single-quoted string literal.
        safe = script.replace("\\", "/").replace("'", "''")
        kwargs.setdefault("nout", 0)
        self.eval(f"run('{safe}')", **kwargs)

    @property
    def workspace(self):
        """A dict-like proxy for the Octave base workspace.

        Supports MATLAB-style variable access::

            octave.workspace['x'] = 5
            octave.workspace['x']   # returns 5.0
            del octave.workspace['x']

        Returns
        -------
        OctaveWorkspaceProxy
        """
        return OctaveWorkspaceProxy(self)

    def restart(self):  # noqa: PLR0912, PLR0915
        """Restart an Octave session in a clean state"""
        if self._engine:
            self._engine.repl.terminate()

        # Close any open writer file handle — its path is tied to the old
        # temp_dir and will be invalid after we create a new one below.
        if self._out_fh and not self._out_fh.closed:
            atexit.unregister(self._out_fh.close)
            self._out_fh.close()
        self._out_fh = None

        # Use the stored executable (may be empty, letting OctaveEngine resolve).
        _executable = self._settings.executable or ""

        # Preserve the SIGINT handler across engine startup.  The underlying
        # pexpect spawn temporarily replaces SIGINT with SIG_DFL so that the
        # Octave child process inherits a clean disposition.  If a concurrent
        # thread (e.g. from a scipy/sympy lazy initialiser) transiently sets
        # SIGINT to SIG_IGN at exactly the wrong moment, pexpect's finally
        # block can "restore" that transient SIG_IGN value, leaving SIGINT
        # permanently ignored for the rest of the Python process (issue #168).
        # Restoring the handler we observed before the spawn prevents engine
        # startup from having any net effect on the caller's SIGINT disposition.
        _saved_sigint = None
        if threading.current_thread() is threading.main_thread():
            with contextlib.suppress(Exception):
                _saved_sigint = signal.getsignal(signal.SIGINT)

        _qt_plugin_path = None
        try:
            # Use a weakref-based wrapper so that OctaveEngine (and its atexit
            # registration) does not hold a strong reference back to this Oct2Py
            # instance, which would otherwise prevent __del__ / exit() from ever
            # being called and cause Octave subprocesses to accumulate.
            #
            # Strip QT_QPA_PLATFORM_PLUGIN_PATH before spawning Octave if it
            # was injected by opencv-python.  opencv injects its own bundled
            # Qt plugin directory (always under a "cv2" package path) into
            # this variable; pexpect inherits os.environ, so the Octave child
            # process would pick up the incompatible path and crash with
            # "Could not load the Qt platform plugin" (issue #240).
            # System-set paths (e.g. from the octave_kernel CI action on
            # macOS) are safe to keep — stripping them breaks octave_kernel's
            # _validate_executable, which needs to run octave successfully.
            _qt_path = os.environ.get("QT_QPA_PLATFORM_PLUGIN_PATH", "")
            _qt_plugin_path = (
                os.environ.pop("QT_QPA_PLATFORM_PLUGIN_PATH") if "cv2" in _qt_path else None
            )
            _weak_self = weakref.ref(self)

            def _stdin_handler(line):
                inst = _weak_self()
                if inst is not None:
                    return inst._handle_stdin(line)
                return None

            self._engine = OctaveEngine(
                executable=_executable,
                stdin_handler=_stdin_handler,
                logger=self.logger,
                cli_options=self._settings.extra_cli_options,
                load_octaverc=self._settings.load_octaverc,
            )
        except Exception as e:
            raise Oct2PyError(str(e)) from None
        finally:
            if _saved_sigint is not None:
                with contextlib.suppress(Exception):
                    signal.signal(signal.SIGINT, _saved_sigint)
            if _qt_plugin_path is not None:
                os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = _qt_plugin_path

        self._settings.executable = self._engine.executable
        _augment_path_for_windows(self._settings.executable)

        # Set up the temp directory for MAT file exchange.
        if self._settings.temp_dir is None:
            # Prefer a RAM-based filesystem (tmpfs) for faster file I/O.
            # On Linux, /dev/shm is always in RAM and avoids disk latency,
            # which is critical for performance in Octave 7+ where save/load
            # can be significantly slower on disk-backed filesystems.
            executable = self._engine.executable
            sandboxed = "snap" in executable or "flatpak" in executable
            shm = "/dev/shm"  # noqa: S108
            if not sandboxed and osp.isdir(shm) and os.access(shm, os.W_OK):
                self._settings.temp_dir = tempfile.mkdtemp(dir=shm, prefix="oct2py_")
                atexit.register(shutil.rmtree, self._settings.temp_dir, True)
            elif sys.platform == "darwin" and not sandboxed and self._settings.ramdisk_size_mb > 0:
                device, mount = _create_macos_ramdisk(self._settings.ramdisk_size_mb)
                if device:
                    self._ramdisk_device = device
                    self._settings.temp_dir = tempfile.mkdtemp(dir=mount, prefix="oct2py_")
                    atexit.register(shutil.rmtree, self._settings.temp_dir, True)
                    atexit.register(_detach_macos_ramdisk, device)
            if self._settings.temp_dir is None:
                self._settings.temp_dir = os.path.join(self._engine.tmp_dir, "oct2py")
                os.makedirs(self._settings.temp_dir, exist_ok=True)
            self._temp_dir_owner = True

        # Pre-open writer.mat so the file descriptor is reused across calls,
        # avoiding repeated open/close syscall overhead.
        if self._out_fh is None or self._out_fh.closed:  # type: ignore[unreachable]
            self._out_fh = open(osp.join(self._settings.temp_dir, "writer.mat"), "w+b")  # noqa: SIM115
        # Ensure the handle is closed before shutil.rmtree fires at interpreter
        # exit.  On Windows, open files cannot be deleted (PermissionError:
        # [WinError 32]).  atexit is LIFO, so registering here (after the
        # engine's rmtree registration) guarantees _out_fh.close runs first.
        # Register the file handle's .close method directly — unlike a bound
        # Oct2Py method, it does not hold a strong reference back to self, so
        # __del__ can still fire normally when the session goes out of scope.
        atexit.register(self._out_fh.close)

        # Add local Octave scripts.
        self._engine.eval('addpath("%s");' % HERE.replace(osp.sep, "/"))

        # Octave's default max_recursion_depth is 256, which is lower than
        # MATLAB's default and causes deep recursive functions to crash the
        # session.  Raise it to match a more permissive default (issue #326).
        self._engine.eval("max_recursion_depth(2500);")

    def _feval(  # noqa
        self,
        func_name,
        func_args=(),
        dname="",
        nout=0,
        timeout=None,
        stream_handler=None,
        store_as="",
        plot_dir=None,
    ):
        """Run the given function with the given args."""
        engine = self._engine
        if engine is None:
            msg = "Session is closed"
            raise Oct2PyError(msg)

        # Set up our mat file paths.
        out_file = osp.join(self._settings.temp_dir, "writer.mat")
        out_file = out_file.replace(osp.sep, "/")
        in_file = osp.join(self._settings.temp_dir, "reader.mat")
        in_file = in_file.replace(osp.sep, "/")

        func_args = list(func_args)
        ref_indices = []
        for i, value in enumerate(func_args):
            if isinstance(value, OctavePtr):
                ref_indices.append(i + 1)
                func_args[i] = value.address
        ref_arr = np.array(ref_indices)

        # Save the request data to the output file.
        req = dict(
            func_name=func_name,
            func_args=tuple(func_args),
            dname=dname or "",
            nout=nout,
            store_as=store_as or "",
            ref_indices=ref_arr,
        )

        write_file(
            req,
            self._out_fh,
            oned_as=self._settings.oned_as,
            convert_to_float=self._settings.convert_to_float,
        )

        # Set up the engine and evaluate the `_pyeval()` function.
        engine.line_handler = stream_handler or self.logger.info
        if timeout is None:
            timeout = self._settings.timeout

        try:
            engine.eval(f'_pyeval("{out_file}", "{in_file}");', timeout=timeout)
        except KeyboardInterrupt:
            stream_handler(engine.repl.interrupt())
            raise
        except TIMEOUT:
            stream_handler(engine.repl.interrupt())
            msg = "Timed out, interrupting"
            raise Oct2PyError(msg) from None
        except EOF:
            if not self._engine:
                return
            stream_handler(engine.repl.child.before)
            self.restart()
            msg = "Session died, restarting"
            raise Oct2PyError(msg) from None

        # Read in the output.
        resp = read_file(in_file, self)
        if resp["err"]:
            msg = self._parse_error(resp["err"])
            raise Oct2PyError(msg)

        result = resp["result"].ravel().tolist()
        if isinstance(result, list) and len(result) == 1:
            result = result[0]

        # Check for sentinel value.
        if (
            isinstance(result, Cell)
            and result.size == 1
            and isinstance(result[0], str)
            and result[0] == "__no_value__"
        ):
            result = None

        if plot_dir:
            engine.make_figures(plot_dir)
        elif self._settings.auto_show:
            self._show_figures()

        return result

    def _parse_error(self, err):
        """Create a traceback for an Octave evaluation error."""
        self.logger.debug(err)
        stack = err.get("stack", [])
        if not err["message"].startswith("parse error:"):
            err["message"] = "error: " + err["message"]
        errmsg = "Octave evaluation error:\n%s" % err["message"]

        if not isinstance(stack, StructArray):
            return errmsg

        errmsg += "\nerror: called from:"
        for item in stack[:-1]:
            errmsg += "\n    %(name)s at line %(line)d" % item
            try:  # noqa
                errmsg += ", column %(column)d" % item
            except Exception:  # noqa
                pass
        return errmsg

    def _handle_stdin(self, line):
        """Handle a stdin request from the session."""
        return input(line.replace(STDIN_PROMPT, ""))

    def _print_doc(self, name):
        """
        Print the documentation of an Octave procedure or object.

        Parameters
        ----------
        name : str
            Function name to search for.
        """
        print(self._get_doc(name))  # noqa

    def _get_doc(self, name):
        """
        Get the documentation of an Octave procedure or object.

        Parameters
        ----------
        name : str
            Function name to search for.

        Returns
        -------
        out : str
          Documentation string.

        Raises
        ------
        Oct2PyError
           If the procedure or object function has a syntax error.

        """
        doc = "No documentation for %s" % name

        engine = self._engine
        if not engine:
            msg = "Session is not open"
            raise Oct2PyError(msg)
        doc = engine.eval('help("%s")' % name, silent=True)

        if "syntax error:" in doc.lower():
            raise Oct2PyError(doc)

        if "error:" in doc.lower():
            doc = engine.eval('type("%s")' % name, silent=True)
            doc = "\n".join(doc.splitlines()[:3])

        default = self.feval.__doc__
        default = (
            "        " + default[default.find("func_args:") :]  # type:ignore[index,union-attr]
        )
        default = "\n".join([line[8:] for line in default.splitlines()])

        doc = "\n".join(doc.splitlines())
        doc = "\n" + doc + "\n\nParameters\n----------\n" + default
        doc += "\n**kwargs - Deprecated keyword arguments\n\n"
        doc += "Notes\n-----\n"
        doc += "Keyword arguments to dynamic functions are deprecated.\n"
        doc += "The `plot_*` kwargs will be ignored, but the rest will\n"
        doc += "used as key - value pairs as in version 3.x.\n"
        doc += "Pass `plot_dir` to `feval` or `eval` for inline plot capture,\n"
        doc += "and use `func_args` directly for key - value pairs."
        return doc

    def _exist(self, name):
        """Test whether a name exists and return the name code.

        Raises an error when the name does not exist.
        """
        cmd = 'exist("%s")' % name
        if not self._engine:
            msg = "Session is not open"
            raise Oct2PyError(msg)
        resp = self._engine.eval(cmd, silent=True).strip()
        exist = int(resp.split()[-1])
        if exist == 0:
            cmd = "class(%s)" % name
            resp = self._engine.eval(cmd, silent=True).strip()
            if "error:" not in resp:
                exist = 2
        return exist

    def _isobject(self, name, exist):
        """Test whether the name is an object."""
        if exist in [2, 5]:
            return False
        cmd = "isobject(%s)" % name
        if not self._engine:
            msg = "Session is not open"
            raise Oct2PyError(msg)
        resp = self._engine.eval(cmd, silent=True).strip()
        return resp == "ans =  1"

    def _get_function_ptr(self, name):
        """Get or create a function pointer of the given name."""
        func = _make_function_ptr_instance
        self._function_ptrs.setdefault(name, func(self, name))
        return self._function_ptrs[name]

    def _get_user_class(self, name, attrs=None):
        """Get or create a user class of the given type."""
        if name not in self._user_classes:
            self._user_classes[name] = _make_user_class(self, name, attrs=attrs)
        return self._user_classes[name]

    def __getattr__(self, attr):
        """Automatically creates a wrapper to an Octave function or object.

        Adapted from the mlabwrap project.
        """
        # needed for help(Oct2Py())
        if attr.startswith("__"):
            return super().__getattr__(attr)  # type:ignore[misc]

        # close_ -> close
        name = attr[:-1] if attr[-1] == "_" else attr

        if self._engine is None:
            msg = "Session is closed"
            raise Oct2PyError(msg)

        # Make sure the name exists.
        exist = self._exist(name)

        if exist not in [2, 3, 5, 103]:
            if exist in (0, 7):
                # Name not found or is a directory — may be an Octave package
                # namespace (+package). Return a lazy proxy; Octave will report
                # an error at call time if the name is truly invalid.
                return _make_namespace_proxy(self, name)
            msg = 'Name "%s" is not a valid callable, use `pull` for variables'
            raise Oct2PyError(msg % name)

        if name == "clear":
            msg = 'Cannot use `clear` command directly, use `eval("clear(var1, var2)")`'
            raise Oct2PyError(msg)

        # Check for user defined class.
        if self._isobject(name, exist):
            obj = self._get_user_class(name)
        else:
            obj = self._get_function_ptr(name)

        # !!! attr, *not* name, because we might have python keyword name!
        # Don't cache namespace proxies — the namespace isn't resolved yet.
        if not isinstance(obj, OctaveNamespaceProxy):
            setattr(self, attr, obj)

        return obj

    def _get_max_nout(self, func_path):
        """Get or count maximum nout of .m function."""

        if not osp.isabs(func_path):
            func_path = self.which(func_path)

        nout = 0  # default nout of eval
        status = "NOT FUNCTION"
        if func_path.endswith(".m"):  # only if `func_path` is .m file
            with open(func_path, encoding="utf8") as fid:
                for line in fid:
                    if line[0] != "f":  # noqa # not function
                        if status == "NOT FUNCTION":
                            continue
                    line = line.translate(  # noqa
                        str.maketrans("", "", "[]()")
                    ).split()  # type:ignore[assignment]
                    try:  # noqa
                        line.remove("function")  # type:ignore[attr-defined]
                    except Exception:  # noqa
                        pass
                    for char in line:
                        if char == "...":
                            status = "FUNCTION"
                            continue
                        if char != "=":
                            nout += 1
                        else:
                            return nout

        return nout

Attributes

logger property writable

The logging instance used by the session.

settings property writable

The session's current settings.

workspace property

A dict-like proxy for the Octave base workspace.

Supports MATLAB-style variable access::

octave.workspace['x'] = 5
octave.workspace['x']   # returns 5.0
del octave.workspace['x']

Returns:

Type Description
OctaveWorkspaceProxy

Functions

__enter__()

Return octave object, restart session if necessary

Source code in oct2py/core.py
271
272
273
274
275
def __enter__(self):
    """Return octave object, restart session if necessary"""
    if not self._engine:
        self.restart()
    return self

__exit__(type_, value, traceback)

Close session

Source code in oct2py/core.py
277
278
279
def __exit__(self, type_, value, traceback):
    """Close session"""
    self.exit()

__del__()

Delete session

Source code in oct2py/core.py
281
282
283
284
285
286
def __del__(self):
    """Delete session"""
    try:  # noqa: SIM105
        self.exit()
    except Exception:  # noqa: S110  # pragma: no cover
        pass

exit()

Quits this octave session and cleans up.

Source code in oct2py/core.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def exit(self):
    """Quits this octave session and cleans up."""
    if self._engine:
        if callable(atexit.unregister):
            atexit.unregister(self._engine._cleanup)
        self._engine.repl.terminate()
    self._engine = None
    if self._out_fh and not self._out_fh.closed:
        atexit.unregister(self._out_fh.close)
        self._out_fh.close()
        self._out_fh = None
    if self._temp_dir_owner and self._settings.temp_dir and osp.isdir(self._settings.temp_dir):
        shutil.rmtree(self._settings.temp_dir, ignore_errors=True)
        self._settings.temp_dir = None
        self._temp_dir_owner = False
    if self._ramdisk_device:
        _detach_macos_ramdisk(self._ramdisk_device)
        self._ramdisk_device = None

push(name, var, timeout=None, verbose=True)

Put a variable or variables into the Octave session.

Parameters:

Name Type Description Default
name str or list

Name of the variable(s).

required
var object or list

The value(s) to pass.

required
timeout float

Time to wait for response from Octave (per line).

None
verbose

Log Octave output at INFO level. If False, log at DEBUG level.

True

Examples:

>>> from oct2py import octave
>>> y = [1, 2]
>>> octave.push('y', y)
>>> octave.pull('y')
array([[1., 2.]])
>>> octave.push(['x', 'y'], ['spam', [1, 2, 3, 4]])
>>> octave.pull(['x', 'y'])
[u'spam', array([[1, 2, 3, 4]])]
Notes

Integer type arguments will be converted to floating point unless convert_to_float=False.

Source code in oct2py/core.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def push(self, name, var, timeout=None, verbose=True):
    """
    Put a variable or variables into the Octave session.

    Parameters
    ----------
    name : str or list
        Name of the variable(s).
    var : object or list
        The value(s) to pass.
    timeout : float
        Time to wait for response from Octave (per line).
    verbose: bool
         Log Octave output at INFO level.  If False, log at DEBUG level.

    Examples
    --------
    >>> from oct2py import octave
    >>> y = [1, 2]
    >>> octave.push('y', y)
    >>> octave.pull('y')
    array([[1., 2.]])
    >>> octave.push(['x', 'y'], ['spam', [1, 2, 3, 4]])
    >>> octave.pull(['x', 'y'])  # doctest: +SKIP
    [u'spam', array([[1, 2, 3, 4]])]

    Notes
    -----
    Integer type arguments will be converted to floating point
    unless `convert_to_float=False`.

    """
    timeout = timeout if timeout is not None else self._settings.timeout
    if isinstance(name, str):
        name = [name]
        var = [var]

    for n, v in zip(name, var, strict=False):
        self.feval("assignin", "base", n, v, nout=0, timeout=timeout, verbose=verbose)

pull(var, timeout=None, verbose=True)

Retrieve a value or values from the Octave session.

Parameters:

Name Type Description Default
var str or list

Name of the variable(s) to retrieve.

required
timeout float, optional.

Time to wait for response from Octave (per line).

None
verbose

Log Octave output at INFO level. If False, log at DEBUG level.

True

Returns:

Name Type Description
out object

Object returned by Octave.

Raises:

Type Description
Oct2PyError

If the variable does not exist in the Octave session.

Examples:

from oct2py import octave y = [1, 2] octave.push('y', y) octave.pull('y') array([[1., 2.]]) octave.push(['x', 'y'], ['spam', [1, 2, 3, 4]]) octave.pull(['x', 'y']) # doctest: +SKIP [u'spam', array([[1, 2, 3, 4]])]

Source code in oct2py/core.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
def pull(self, var, timeout=None, verbose=True):
    """
    Retrieve a value or values from the Octave session.

    Parameters
    ----------
    var : str or list
        Name of the variable(s) to retrieve.
    timeout : float, optional.
        Time to wait for response from Octave (per line).
    verbose: bool
         Log Octave output at INFO level.  If False, log at DEBUG level.

    Returns
    -------
    out : object
        Object returned by Octave.

    Raises
    ------
    Oct2PyError
        If the variable does not exist in the Octave session.

    Examples
    --------
      >>> from oct2py import octave
      >>> y = [1, 2]
      >>> octave.push('y', y)
      >>> octave.pull('y')
      array([[1., 2.]])
      >>> octave.push(['x', 'y'], ['spam', [1, 2, 3, 4]])
      >>> octave.pull(['x', 'y'])  # doctest: +SKIP
      [u'spam', array([[1, 2, 3, 4]])]

    """
    timeout = timeout if timeout is not None else self._settings.timeout
    if isinstance(var, str):
        var = [var]
    outputs = []
    for name in var:
        exist = self._exist(name)
        if exist == 1:
            outputs.append(self.feval("evalin", "base", name, timeout=timeout, verbose=verbose))
        else:
            outputs.append(self.get_pointer(name, timeout=timeout))

    if len(outputs) == 1:
        return outputs[0]
    return outputs

get_pointer(name, timeout=None, expr=False)

Get a pointer to a named object in the Octave workspace.

Parameters:

Name Type Description Default
name

The name of the object in the Octave workspace, or an Octave expression string when expr=True.

required
timeout

Time to wait for response from Octave (per line).

None
expr

If True, treat name as an Octave expression string rather than a variable name. The expression is assigned to a unique temporary variable in the Octave workspace and a pointer to that variable is returned. Use this when you need to pass an expression that cannot be converted to a Python object (e.g. cell arrays of function handles like {@cos @sin}).

Note: the temporary variable persists in the Octave workspace for the lifetime of the session.

False

Examples:

>>> from oct2py import octave
>>> octave.eval('foo = [1, 2];')
>>> ptr = octave.get_pointer('foo')
>>> ptr.value
array([[1., 2.]])
>>> ptr.address
'foo'
>>> # Can be passed as an argument
>>> octave.disp(ptr)
1  2
>>> from oct2py import octave
>>> sin = octave.get_pointer('sin')  # equivalent to `octave.sin`
>>> sin.address
'@sin'
>>> x = octave.quad(sin, 0, octave.pi())
>>> x
2.0
>>> from oct2py import octave
>>> ptr = octave.get_pointer('{@cos @sin}', expr=True)
>>> type(ptr).__name__
'OctaveVariablePtr'
>>> # Pass the cell of function handles to an Octave function
>>> octave.feval('cellfun', '@(f) f(0)', ptr)
Notes

Pointers can be passed to feval or dynamic functions as function arguments. A pointer passed as a nested value will be passed by value instead.

Raises:

Type Description
Oct2PyError

If the variable does not exist in the Octave session or is of unknown type.

Returns:

Type Description
A variable, object, user class, or function pointer as appropriate.
Source code in oct2py/core.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
def get_pointer(self, name, timeout=None, expr=False):
    """Get a pointer to a named object in the Octave workspace.

    Parameters
    ----------
    name: str
        The name of the object in the Octave workspace, or an Octave
        expression string when ``expr=True``.
    timeout: float, optional.
        Time to wait for response from Octave (per line).
    expr: bool, optional (default False)
        If True, treat `name` as an Octave expression string rather than a
        variable name. The expression is assigned to a unique temporary
        variable in the Octave workspace and a pointer to that variable is
        returned. Use this when you need to pass an expression that cannot
        be converted to a Python object (e.g. cell arrays of function
        handles like ``{@cos @sin}``).

        Note: the temporary variable persists in the Octave workspace for
        the lifetime of the session.

    Examples
    --------
    >>> from oct2py import octave
    >>> octave.eval('foo = [1, 2];')
    >>> ptr = octave.get_pointer('foo')
    >>> ptr.value
    array([[1., 2.]])
    >>> ptr.address
    'foo'
    >>> # Can be passed as an argument
    >>> octave.disp(ptr)  # doctest: +SKIP
    1  2

    >>> from oct2py import octave
    >>> sin = octave.get_pointer('sin')  # equivalent to `octave.sin`
    >>> sin.address
    '@sin'
    >>> x = octave.quad(sin, 0, octave.pi())
    >>> x
    2.0

    >>> from oct2py import octave
    >>> ptr = octave.get_pointer('{@cos @sin}', expr=True)
    >>> type(ptr).__name__
    'OctaveVariablePtr'
    >>> # Pass the cell of function handles to an Octave function
    >>> octave.feval('cellfun', '@(f) f(0)', ptr)  # doctest: +SKIP

    Notes
    -----
    Pointers can be passed to `feval` or dynamic functions as function
    arguments.  A pointer passed as a nested value will be passed by value
    instead.

    Raises
    ------
    Oct2PyError
        If the variable does not exist in the Octave session or is of
        unknown type.

    Returns
    -------
    A variable, object, user class, or function pointer as appropriate.
    """
    timeout = timeout if timeout is not None else self._settings.timeout
    if expr:
        tmp_name = f"_oct2py_expr_{uuid.uuid4().hex}"
        self.eval(f"{tmp_name} = {name}", timeout=timeout)
        return _make_variable_ptr_instance(self, tmp_name)

    exist = self._exist(name)
    isobject = self._isobject(name, exist)

    if exist == 0:
        raise Oct2PyError('"%s" is undefined' % name)

    elif exist == 1:
        return _make_variable_ptr_instance(self, name)

    elif isobject:
        return self._get_user_class(name)

    elif exist in [2, 3, 5]:
        return self._get_function_ptr(name)

    raise Oct2PyError('Unknown type for object "%s"' % name)

extract_figures(plot_dir, remove=False)

Extract the figures in the directory to IPython display objects.

Parameters:

Name Type Description Default
plot_dir

The plot dir where the figures were created.

required
remove

Whether to remove the plot directory after saving.

False

Returns:

Type Description
The list of figure objects.
Source code in oct2py/core.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
def extract_figures(self, plot_dir, remove=False):
    """Extract the figures in the directory to IPython display objects.

    Parameters
    ----------
    plot_dir: str
        The plot dir where the figures were created.
    remove: bool, optional.
        Whether to remove the plot directory after saving.

    Returns
    -------
    The list of figure objects.
    """
    if not self._engine:
        msg = "Session is not open"
        raise Oct2PyError(msg)
    figures = self._engine.extract_figures(plot_dir, remove)
    return figures

show()

Render open Octave figures and display them using matplotlib.

Captures all currently open Octave figure windows as PNG images and displays them via :func:matplotlib.pyplot.imshow. This is useful in environments such as PyCharm that can display matplotlib figures inline but cannot show Octave's native figure windows.

Requires matplotlib to be installed. If it is not available, the method returns silently.

This is called automatically after each eval/feval when auto_show=True (which is the default inside PyCharm).

Examples:

>>> import oct2py
>>> oc = oct2py.Oct2Py()
>>> _ = oc.plot([1, 2, 3])
>>> oc.show()  # displays the Octave figure inline
Source code in oct2py/core.py
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
def show(self):
    """Render open Octave figures and display them using matplotlib.

    Captures all currently open Octave figure windows as PNG images and
    displays them via :func:`matplotlib.pyplot.imshow`.  This is useful
    in environments such as PyCharm that can display matplotlib figures
    inline but cannot show Octave's native figure windows.

    Requires ``matplotlib`` to be installed.  If it is not available,
    the method returns silently.

    This is called automatically after each eval/feval when
    ``auto_show=True`` (which is the default inside PyCharm).

    Examples
    --------
    >>> import oct2py  # doctest: +SKIP
    >>> oc = oct2py.Oct2Py()  # doctest: +SKIP
    >>> _ = oc.plot([1, 2, 3])  # doctest: +SKIP
    >>> oc.show()  # displays the Octave figure inline  # doctest: +SKIP
    """
    self._show_figures()

feval(func_path, *func_args, **kwargs)

Run a function in Octave and return the result.

Parameters:

Name Type Description Default
func_path str

Name of function to run or a path to an m-file.

required
func_args object

Args to send to the function.

()

Other Parameters:

Name Type Description
nout int or str

The desired number of returned values, defaults to 1. If nout value is 'max_nout', _get_max_nout() will be used.

quiet bool

If True, execute the function but do not capture or return any output. Takes precedence over nout.

store_as str

If given, saves the result to the given Octave variable name instead of returning it.

verbose bool

Log Octave output at INFO level. If False, log at DEBUG level.

stream_handler callable

A function that is called for each line of output from the evaluation.

timeout float

The timeout in seconds for the call.

plot_dir str

If specified, save the session's plot figures to the plot directory instead of displaying the plot window.

plot_backend str

The plotting back end to use.

plot_name str

Saved plots will start with plot_name and end with "_%%.xxx' where %% is the plot number and xxx is the plot_format.

plot_format str

The format in which to save the plot.

plot_width int

The plot width in pixels.

plot_height int

The plot height in pixels.

Notes

The function arguments passed follow Octave calling convention, not Python. That is, all values must be passed as a comma separated list, not using x=foo assignment.

Plot rendering limitation (issue #172): oct2py executes Octave synchronously, so figure updates triggered by pause() calls inside a .m function are not rendered mid-execution — plots are only exposed after the entire function returns. For interactive display this means figures appear at the end of the call, not incrementally. To capture figures from inside a .m file programmatically, pass plot_dir and then call :meth:extract_figures::

plot_dir = tempfile.mkdtemp()
octave.feval("my_func.m", plot_dir=plot_dir)
imgs = octave.extract_figures(plot_dir)

Examples:

>>> from oct2py import octave
>>> cell = octave.feval('cell', 10, 10, 10)
>>> cell.shape
(10, 10, 10)
>>> from oct2py import octave
>>> x = octave.feval('linspace', 0, octave.pi() / 2)
>>> x.shape
(1, 100)
>>> from oct2py import octave
>>> x = octave.feval('svd', octave.hilb(3))
>>> x
array([[1.40831893],
       [0.12232707],
       [0.00268734]])
>>> # specify three return values
>>> (u, v, d) = octave.feval('svd', octave.hilb(3), nout=3)
>>> u.shape
(3, 3)

Returns:

Type Description
The Python value(s) returned by the Octave function call.
Source code in oct2py/core.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
def feval(self, func_path, *func_args, **kwargs):
    """Run a function in Octave and return the result.

    Parameters
    ----------
    func_path : str
        Name of function to run or a path to an m-file.
    func_args : object, optional
        Args to send to the function.

    Other Parameters
    ----------------
    nout : int or str, optional
        The desired number of returned values, defaults to 1. If nout
        value is 'max_nout', _get_max_nout() will be used.
    quiet : bool, optional
        If True, execute the function but do not capture or return any
        output.  Takes precedence over ``nout``.
    store_as : str, optional
        If given, saves the result to the given Octave variable name
        instead of returning it.
    verbose : bool, optional
        Log Octave output at INFO level.  If False, log at DEBUG level.
    stream_handler : callable, optional
        A function that is called for each line of output from the
        evaluation.
    timeout : float, optional
        The timeout in seconds for the call.
    plot_dir : str, optional
        If specified, save the session's plot figures to the plot
        directory instead of displaying the plot window.
    plot_backend : str, optional
        The plotting back end to use.
    plot_name : str, optional
        Saved plots will start with `plot_name` and
        end with "_%%.xxx' where %% is the plot number and
        xxx is the `plot_format`.
    plot_format : str, optional
        The format in which to save the plot.
    plot_width : int, optional
        The plot width in pixels.
    plot_height : int, optional
        The plot height in pixels.

    Notes
    -----
    The function arguments passed follow Octave calling convention, not
    Python. That is, all values must be passed as a comma separated list,
    not using `x=foo` assignment.

    **Plot rendering limitation (issue #172):** oct2py executes Octave
    synchronously, so figure updates triggered by ``pause()`` calls inside
    a ``.m`` function are not rendered mid-execution — plots are only
    exposed after the entire function returns.  For interactive display
    this means figures appear at the end of the call, not incrementally.
    To capture figures from inside a ``.m`` file programmatically, pass
    ``plot_dir`` and then call :meth:`extract_figures`::

        plot_dir = tempfile.mkdtemp()
        octave.feval("my_func.m", plot_dir=plot_dir)
        imgs = octave.extract_figures(plot_dir)

    Examples
    --------
    >>> from oct2py import octave
    >>> cell = octave.feval('cell', 10, 10, 10)
    >>> cell.shape
    (10, 10, 10)

    >>> from oct2py import octave
    >>> x = octave.feval('linspace', 0, octave.pi() / 2)
    >>> x.shape
    (1, 100)

    >>> from oct2py import octave
    >>> x = octave.feval('svd', octave.hilb(3))
    >>> x
    array([[1.40831893],
           [0.12232707],
           [0.00268734]])
    >>> # specify three return values
    >>> (u, v, d) = octave.feval('svd', octave.hilb(3), nout=3)
    >>> u.shape
    (3, 3)

    Returns
    -------
    The Python value(s) returned by the Octave function call.
    """  # noqa: DOC102, DOC103
    if not self._engine:
        msg = "Session is not open"
        raise Oct2PyError(msg)

    # nout handler
    nout = kwargs.get("nout")
    if kwargs.get("quiet"):
        nout = -1
    elif nout is None:
        nout = 1
    elif nout == "max_nout":
        nout = self._get_max_nout(func_path)

    plot_dir = kwargs.get("plot_dir")

    # Choose appropriate plot backend.
    default_backend = "inline" if plot_dir else self._settings.backend
    backend = kwargs.get("plot_backend", default_backend)
    # Map "disable" to "inline" so octave_kernel sets defaultfigurevisible=off.
    if backend == "disable":
        backend = "inline"

    settings = dict(
        backend=backend,
        format=kwargs.get("plot_format"),
        name=kwargs.get("plot_name"),
        width=kwargs.get("plot_width"),
        height=kwargs.get("plot_height"),
        resolution=kwargs.get("plot_res"),
    )
    self._engine.plot_settings = settings

    _is_dotted_name = kwargs.pop("_is_dotted_name", False)
    if _is_dotted_name:
        func_name = func_path
        dname = ""
    else:
        dname = osp.dirname(func_path)
        fname = osp.basename(func_path)
        func_name, ext = osp.splitext(fname)
        if ext and ext != ".m":
            msg = "Need to give path to .m file"
            raise TypeError(msg)

    if func_name == "clear":
        msg = 'Cannot use `clear` command directly, use eval("clear(var1, var2)")'
        raise Oct2PyError(msg)

    stream_handler = kwargs.get("stream_handler")
    verbose = kwargs.get("verbose", True)
    store_as = kwargs.get("store_as", "")
    _t = kwargs.get("timeout")
    timeout = _t if _t is not None else self._settings.timeout
    if not stream_handler:
        stream_handler = self.logger.info if verbose else self.logger.debug

    return self._feval(
        func_name,
        func_args,
        dname=dname,
        nout=nout,
        timeout=timeout,
        stream_handler=stream_handler,
        store_as=store_as,
        plot_dir=plot_dir,
    )

eval(cmds, verbose=True, timeout=None, stream_handler=None, temp_dir=None, plot_dir=None, plot_name=None, plot_format=None, plot_backend=None, plot_width=None, plot_height=None, plot_res=None, nout=0, quiet=False, **kwargs)

Evaluate an Octave command or commands.

Parameters:

Name Type Description Default
cmds str or list

Commands(s) to pass to Octave.

required
verbose bool

Log Octave output at INFO level. If False, log at DEBUG level.

True
stream_handler

A function that is called for each line of output from the evaluation.

None
timeout float

Time to wait for response from Octave (per line). If not given, the instance timeout is used.

None
nout int or str, optional.

The desired number of returned values, defaults to 0. If nout is 0, the ans will be returned as the return value. If nout value is 'max_nout', _get_max_nout() will be used.

0
quiet bool

If True, execute the command(s) but do not capture or return any output. Useful when ans is not serialisable, or to avoid double-printing in Jupyter. Takes precedence over nout.

False
temp_dir

If specified, the session's MAT files will be created in the directory, otherwise a the instance temp_dir is used. a shared memory (tmpfs) path.

None
plot_dir

If specified, save the session's plot figures to the plot directory instead of displaying the plot window.

None
plot_name str

Saved plots will start with plot_name and end with "_%%.xxx' where %% is the plot number and xxx is the plot_format.

None
plot_format

The format in which to save the plot (PNG by default).

None
plot_width

The plot with in pixels.

None
plot_height

The plot height in pixels.

None
plot_backend

The plot backend to use.

None
plot_res

The plot resolution in pixels per inch.

None
**kwargs
{}

Examples:

>>> from oct2py import octave
>>> octave.eval('disp("hello")')
hello
>>> x = octave.eval('round(quad(@sin, 0, pi/2));')
>>> x
1.0
>>> a = octave.eval('disp("hello");1;')
hello
>>> a = octave.eval('disp("hello");1;', verbose=False)
>>> a
1.0
>>> from oct2py import octave
>>> lines = []
>>> octave.eval('for i = 1:3; disp(i);end',                         stream_handler=lines.append)
>>> lines
[' 1', ' 2', ' 3']

Returns:

Name Type Description
out object

Octave "ans" variable, or None.

Notes

The deprecated log kwarg will temporarily set the logger level to WARN. Using the logger settings directly is preferred. The deprecated return_both kwarg will still work, but the preferred method is to use the stream_handler. If stream_handler is given, the return_both kwarg will be honored but will give an empty string as the response.

Raises:

Type Description
Oct2PyError

If the command(s) fail.

Source code in oct2py/core.py
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
def eval(  # noqa: PLR0913
    self,
    cmds,
    verbose=True,
    timeout=None,
    stream_handler=None,
    temp_dir=None,
    plot_dir=None,
    plot_name=None,
    plot_format=None,
    plot_backend=None,
    plot_width=None,
    plot_height=None,
    plot_res=None,
    nout=0,
    quiet=False,
    **kwargs,
):
    """Evaluate an Octave command or commands.

    Parameters
    ----------
    cmds : str or list
        Commands(s) to pass to Octave.
    verbose : bool, optional
         Log Octave output at INFO level.  If False, log at DEBUG level.
    stream_handler: callable, optional
        A function that is called for each line of output from the
        evaluation.
    timeout : float, optional
        Time to wait for response from Octave (per line).  If not given,
        the instance `timeout` is used.
    nout : int or str, optional.
        The desired number of returned values, defaults to 0.  If nout
        is 0, the `ans` will be returned as the return value. If nout
        value is 'max_nout', _get_max_nout() will be used.
    quiet : bool, optional
        If True, execute the command(s) but do not capture or return any
        output.  Useful when ``ans`` is not serialisable, or to avoid
        double-printing in Jupyter.  Takes precedence over ``nout``.
    temp_dir: str, optional
        If specified, the session's MAT files will be created in the
        directory, otherwise a the instance `temp_dir` is used.
        a shared memory (tmpfs) path.
    plot_dir: str, optional
        If specified, save the session's plot figures to the plot
        directory instead of displaying the plot window.
    plot_name : str, optional
        Saved plots will start with `plot_name` and
        end with "_%%.xxx' where %% is the plot number and
        xxx is the `plot_format`.
    plot_format: str, optional
        The format in which to save the plot (PNG by default).
    plot_width: int, optional
        The plot with in pixels.
    plot_height: int, optional
        The plot height in pixels.
    plot_backend: str, optional
        The plot backend to use.
    plot_res: int, optional
        The plot resolution in pixels per inch.
    **kwargs Deprecated kwargs.

    Examples
    --------
    >>> from oct2py import octave
    >>> octave.eval('disp("hello")') # doctest: +SKIP
    hello
    >>> x = octave.eval('round(quad(@sin, 0, pi/2));')
    >>> x
    1.0

    >>> a = octave.eval('disp("hello");1;')  # doctest: +SKIP
    hello
    >>> a = octave.eval('disp("hello");1;', verbose=False)
    >>> a
    1.0

    >>> from oct2py import octave
    >>> lines = []
    >>> octave.eval('for i = 1:3; disp(i);end', \
                    stream_handler=lines.append)
    >>> lines  # doctest: +SKIP
    [' 1', ' 2', ' 3']

    Returns
    -------
    out : object
        Octave "ans" variable, or None.

    Notes
    -----
    The deprecated `log` kwarg will temporarily set the `logger` level to
    `WARN`.  Using the `logger` settings directly is preferred.
    The deprecated `return_both` kwarg will still work, but the preferred
    method is to use the `stream_handler`.  If `stream_handler` is given,
    the `return_both` kwarg will be honored but will give an empty string
    as the response.

    Raises
    ------
    Oct2PyError
        If the command(s) fail.
    """  # noqa: DOC103
    if isinstance(cmds, str):
        cmds = [cmds]

    timeout = timeout if timeout is not None else self._settings.timeout
    plot_name = plot_name if plot_name is not None else self._settings.plot_name
    plot_format = plot_format if plot_format is not None else self._settings.plot_format
    plot_width = plot_width if plot_width is not None else self._settings.plot_width
    plot_height = plot_height if plot_height is not None else self._settings.plot_height
    plot_res = plot_res if plot_res is not None else self._settings.plot_res

    prev_temp_dir = self._settings.temp_dir
    self._settings.temp_dir = temp_dir or self._settings.temp_dir
    prev_log_level = self.logger.level

    if kwargs.get("log") is False:
        self.logger.setLevel(logging.WARN)

    for name in ["log", "return_both"]:
        if name not in kwargs:
            continue
        msg = "Using deprecated `%s` kwarg, see docs on `Oct2Py.eval()`"
        warnings.warn(msg % name, Oct2PyWarning, stacklevel=2)

    return_both = kwargs.pop("return_both", False)
    lines: list[str] = []
    if return_both and not stream_handler:
        stream_handler = lines.append

    ans = None
    for cmd in cmds:
        resp = self.feval(
            "evalin",
            "base",
            cmd,
            nout=nout,
            quiet=quiet,
            timeout=timeout,
            stream_handler=stream_handler,
            verbose=verbose,
            plot_dir=plot_dir,
            plot_name=plot_name,
            plot_format=plot_format,
            plot_backend=plot_backend,
            plot_width=plot_width,
            plot_height=plot_height,
            plot_res=plot_res,
        )
        if resp is not None:
            ans = resp

    self._settings.temp_dir = prev_temp_dir
    self.logger.setLevel(prev_log_level)

    if return_both:
        return "\n".join(lines), ans
    return ans

run(script, **kwargs)

Run an Octave script file in the base workspace.

Unlike calling octave.run(script) via dynamic dispatch (which runs the script inside a temporary function scope and discards any variables it creates), this method executes the script through evalin('base', ...), so variables assigned by the script persist in the Octave base workspace and can be retrieved with :meth:pull.

Parameters:

Name Type Description Default
script str

Name of the script or path to an .m file, passed directly to Octave's run() built-in.

required
**kwargs

Additional keyword arguments forwarded to :meth:eval (e.g. verbose, timeout, stream_handler).

{}

Examples:

>>> import os, tempfile
>>> from oct2py import Oct2Py
>>> oc = Oct2Py()
>>> with tempfile.NamedTemporaryFile(suffix='.m', mode='w', delete=False) as f:
...     _ = f.write('b = 42;')
...     script_path = f.name
>>> oc.run(script_path)
>>> oc.pull('b')
42.0
>>> oc.exit()
>>> os.unlink(script_path)
Source code in oct2py/core.py
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
def run(self, script, **kwargs):
    """Run an Octave script file in the base workspace.

    Unlike calling ``octave.run(script)`` via dynamic dispatch (which runs
    the script inside a temporary function scope and discards any variables
    it creates), this method executes the script through ``evalin('base',
    ...)``, so variables assigned by the script persist in the Octave base
    workspace and can be retrieved with :meth:`pull`.

    Parameters
    ----------
    script : str
        Name of the script or path to an ``.m`` file, passed directly to
        Octave's ``run()`` built-in.
    **kwargs
        Additional keyword arguments forwarded to :meth:`eval` (e.g.
        ``verbose``, ``timeout``, ``stream_handler``).

    Examples
    --------
    >>> import os, tempfile
    >>> from oct2py import Oct2Py
    >>> oc = Oct2Py()
    >>> with tempfile.NamedTemporaryFile(suffix='.m', mode='w', delete=False) as f:
    ...     _ = f.write('b = 42;')
    ...     script_path = f.name
    >>> oc.run(script_path)
    >>> oc.pull('b')
    42.0
    >>> oc.exit()
    >>> os.unlink(script_path)
    """
    # Escape backslashes and single quotes so the path is safe inside
    # an Octave single-quoted string literal.
    safe = script.replace("\\", "/").replace("'", "''")
    kwargs.setdefault("nout", 0)
    self.eval(f"run('{safe}')", **kwargs)

restart()

Restart an Octave session in a clean state

Source code in oct2py/core.py
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
def restart(self):  # noqa: PLR0912, PLR0915
    """Restart an Octave session in a clean state"""
    if self._engine:
        self._engine.repl.terminate()

    # Close any open writer file handle — its path is tied to the old
    # temp_dir and will be invalid after we create a new one below.
    if self._out_fh and not self._out_fh.closed:
        atexit.unregister(self._out_fh.close)
        self._out_fh.close()
    self._out_fh = None

    # Use the stored executable (may be empty, letting OctaveEngine resolve).
    _executable = self._settings.executable or ""

    # Preserve the SIGINT handler across engine startup.  The underlying
    # pexpect spawn temporarily replaces SIGINT with SIG_DFL so that the
    # Octave child process inherits a clean disposition.  If a concurrent
    # thread (e.g. from a scipy/sympy lazy initialiser) transiently sets
    # SIGINT to SIG_IGN at exactly the wrong moment, pexpect's finally
    # block can "restore" that transient SIG_IGN value, leaving SIGINT
    # permanently ignored for the rest of the Python process (issue #168).
    # Restoring the handler we observed before the spawn prevents engine
    # startup from having any net effect on the caller's SIGINT disposition.
    _saved_sigint = None
    if threading.current_thread() is threading.main_thread():
        with contextlib.suppress(Exception):
            _saved_sigint = signal.getsignal(signal.SIGINT)

    _qt_plugin_path = None
    try:
        # Use a weakref-based wrapper so that OctaveEngine (and its atexit
        # registration) does not hold a strong reference back to this Oct2Py
        # instance, which would otherwise prevent __del__ / exit() from ever
        # being called and cause Octave subprocesses to accumulate.
        #
        # Strip QT_QPA_PLATFORM_PLUGIN_PATH before spawning Octave if it
        # was injected by opencv-python.  opencv injects its own bundled
        # Qt plugin directory (always under a "cv2" package path) into
        # this variable; pexpect inherits os.environ, so the Octave child
        # process would pick up the incompatible path and crash with
        # "Could not load the Qt platform plugin" (issue #240).
        # System-set paths (e.g. from the octave_kernel CI action on
        # macOS) are safe to keep — stripping them breaks octave_kernel's
        # _validate_executable, which needs to run octave successfully.
        _qt_path = os.environ.get("QT_QPA_PLATFORM_PLUGIN_PATH", "")
        _qt_plugin_path = (
            os.environ.pop("QT_QPA_PLATFORM_PLUGIN_PATH") if "cv2" in _qt_path else None
        )
        _weak_self = weakref.ref(self)

        def _stdin_handler(line):
            inst = _weak_self()
            if inst is not None:
                return inst._handle_stdin(line)
            return None

        self._engine = OctaveEngine(
            executable=_executable,
            stdin_handler=_stdin_handler,
            logger=self.logger,
            cli_options=self._settings.extra_cli_options,
            load_octaverc=self._settings.load_octaverc,
        )
    except Exception as e:
        raise Oct2PyError(str(e)) from None
    finally:
        if _saved_sigint is not None:
            with contextlib.suppress(Exception):
                signal.signal(signal.SIGINT, _saved_sigint)
        if _qt_plugin_path is not None:
            os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = _qt_plugin_path

    self._settings.executable = self._engine.executable
    _augment_path_for_windows(self._settings.executable)

    # Set up the temp directory for MAT file exchange.
    if self._settings.temp_dir is None:
        # Prefer a RAM-based filesystem (tmpfs) for faster file I/O.
        # On Linux, /dev/shm is always in RAM and avoids disk latency,
        # which is critical for performance in Octave 7+ where save/load
        # can be significantly slower on disk-backed filesystems.
        executable = self._engine.executable
        sandboxed = "snap" in executable or "flatpak" in executable
        shm = "/dev/shm"  # noqa: S108
        if not sandboxed and osp.isdir(shm) and os.access(shm, os.W_OK):
            self._settings.temp_dir = tempfile.mkdtemp(dir=shm, prefix="oct2py_")
            atexit.register(shutil.rmtree, self._settings.temp_dir, True)
        elif sys.platform == "darwin" and not sandboxed and self._settings.ramdisk_size_mb > 0:
            device, mount = _create_macos_ramdisk(self._settings.ramdisk_size_mb)
            if device:
                self._ramdisk_device = device
                self._settings.temp_dir = tempfile.mkdtemp(dir=mount, prefix="oct2py_")
                atexit.register(shutil.rmtree, self._settings.temp_dir, True)
                atexit.register(_detach_macos_ramdisk, device)
        if self._settings.temp_dir is None:
            self._settings.temp_dir = os.path.join(self._engine.tmp_dir, "oct2py")
            os.makedirs(self._settings.temp_dir, exist_ok=True)
        self._temp_dir_owner = True

    # Pre-open writer.mat so the file descriptor is reused across calls,
    # avoiding repeated open/close syscall overhead.
    if self._out_fh is None or self._out_fh.closed:  # type: ignore[unreachable]
        self._out_fh = open(osp.join(self._settings.temp_dir, "writer.mat"), "w+b")  # noqa: SIM115
    # Ensure the handle is closed before shutil.rmtree fires at interpreter
    # exit.  On Windows, open files cannot be deleted (PermissionError:
    # [WinError 32]).  atexit is LIFO, so registering here (after the
    # engine's rmtree registration) guarantees _out_fh.close runs first.
    # Register the file handle's .close method directly — unlike a bound
    # Oct2Py method, it does not hold a strong reference back to self, so
    # __del__ can still fire normally when the session goes out of scope.
    atexit.register(self._out_fh.close)

    # Add local Octave scripts.
    self._engine.eval('addpath("%s");' % HERE.replace(osp.sep, "/"))

    # Octave's default max_recursion_depth is 256, which is lower than
    # MATLAB's default and causes deep recursive functions to crash the
    # session.  Raise it to match a more permissive default (issue #326).
    self._engine.eval("max_recursion_depth(2500);")

__getattr__(attr)

Automatically creates a wrapper to an Octave function or object.

Adapted from the mlabwrap project.

Source code in oct2py/core.py
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
def __getattr__(self, attr):
    """Automatically creates a wrapper to an Octave function or object.

    Adapted from the mlabwrap project.
    """
    # needed for help(Oct2Py())
    if attr.startswith("__"):
        return super().__getattr__(attr)  # type:ignore[misc]

    # close_ -> close
    name = attr[:-1] if attr[-1] == "_" else attr

    if self._engine is None:
        msg = "Session is closed"
        raise Oct2PyError(msg)

    # Make sure the name exists.
    exist = self._exist(name)

    if exist not in [2, 3, 5, 103]:
        if exist in (0, 7):
            # Name not found or is a directory — may be an Octave package
            # namespace (+package). Return a lazy proxy; Octave will report
            # an error at call time if the name is truly invalid.
            return _make_namespace_proxy(self, name)
        msg = 'Name "%s" is not a valid callable, use `pull` for variables'
        raise Oct2PyError(msg % name)

    if name == "clear":
        msg = 'Cannot use `clear` command directly, use `eval("clear(var1, var2)")`'
        raise Oct2PyError(msg)

    # Check for user defined class.
    if self._isobject(name, exist):
        obj = self._get_user_class(name)
    else:
        obj = self._get_function_ptr(name)

    # !!! attr, *not* name, because we might have python keyword name!
    # Don't cache namespace proxies — the namespace isn't resolved yet.
    if not isinstance(obj, OctaveNamespaceProxy):
        setattr(self, attr, obj)

    return obj

OctaveWorkspaceProxy

oct2py.OctaveWorkspaceProxy

Dict-like proxy for the Octave base workspace.

Allows MATLAB-style variable access::

octave.workspace['x'] = 5
octave.workspace['x']   # returns 5.0
del octave.workspace['x']

Parameters:

Name Type Description Default
session Oct2Py

The Oct2Py session to proxy.

required
Source code in oct2py/core.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class OctaveWorkspaceProxy:
    """Dict-like proxy for the Octave base workspace.

    Allows MATLAB-style variable access::

        octave.workspace['x'] = 5
        octave.workspace['x']   # returns 5.0
        del octave.workspace['x']

    Parameters
    ----------
    session : Oct2Py
        The Oct2Py session to proxy.
    """

    _session: "Oct2Py"

    def __init__(self, session):
        self._session = session

    def __getitem__(self, name):
        """Return the named variable from the Octave workspace."""
        return self._session.pull(name)

    def __setitem__(self, name, value):
        """Set a variable in the Octave workspace."""
        self._session.push(name, value)

    def __delitem__(self, name):
        """Delete a variable from the Octave workspace."""
        exist = self._session._exist(name)
        if exist != 1:
            raise KeyError(name)
        self._session.eval('clear("%s")' % name, verbose=False)

    def __repr__(self):
        """Return a string representation of the proxy."""
        return f"OctaveWorkspaceProxy({self._session!r})"

Functions

__getitem__(name)

Return the named variable from the Octave workspace.

Source code in oct2py/core.py
106
107
108
def __getitem__(self, name):
    """Return the named variable from the Octave workspace."""
    return self._session.pull(name)

__setitem__(name, value)

Set a variable in the Octave workspace.

Source code in oct2py/core.py
110
111
112
def __setitem__(self, name, value):
    """Set a variable in the Octave workspace."""
    self._session.push(name, value)

__delitem__(name)

Delete a variable from the Octave workspace.

Source code in oct2py/core.py
114
115
116
117
118
119
def __delitem__(self, name):
    """Delete a variable from the Octave workspace."""
    exist = self._session._exist(name)
    if exist != 1:
        raise KeyError(name)
    self._session.eval('clear("%s")' % name, verbose=False)

__repr__()

Return a string representation of the proxy.

Source code in oct2py/core.py
121
122
123
def __repr__(self):
    """Return a string representation of the proxy."""
    return f"OctaveWorkspaceProxy({self._session!r})"

Struct

oct2py.Struct

Bases: dict

Octave style struct, enhanced.

Notes

Supports dictionary and attribute style access. Can be pickled, and supports code completion in a REPL.

Examples

from pprint import pprint from oct2py import Struct a = Struct() a.b = 'spam' # a["b"] == 'spam' a.c["d"] = 'eggs' # a.c.d == 'eggs' pprint(a) {'b': 'spam', 'c': {'d': 'eggs'}}

Source code in oct2py/io.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
class Struct(dict):  # type:ignore[type-arg]
    """
    Octave style struct, enhanced.

    Notes
    =====
    Supports dictionary and attribute style access.  Can be pickled,
    and supports code completion in a REPL.

    Examples
    ========
    >>> from pprint import pprint
    >>> from oct2py import Struct
    >>> a = Struct()
    >>> a.b = 'spam'  # a["b"] == 'spam'
    >>> a.c["d"] = 'eggs'  # a.c.d == 'eggs'
    >>> pprint(a)
    {'b': 'spam', 'c': {'d': 'eggs'}}
    """

    def __getattr__(self, attr):
        """Access the dictionary keys for unknown attributes."""
        try:
            return self[attr]
        except KeyError:
            msg = "'Struct' object has no attribute %s" % attr
            raise AttributeError(msg) from None

    def __getitem__(self, attr):
        """Get a dict value; create a Struct if requesting a Struct member."""
        # Do not create a key if the attribute starts with an underscore.
        if attr in self or attr.startswith("_"):
            return dict.__getitem__(self, attr)
        frame = inspect.currentframe()
        if frame is None or frame.f_back is None:
            return None
        # step into the function that called us
        if frame.f_back.f_back and self._is_allowed(frame.f_back.f_back):  # noqa
            dict.__setitem__(self, attr, Struct())
        elif self._is_allowed(frame.f_back):
            dict.__setitem__(self, attr, Struct())
        return dict.__getitem__(self, attr)

    def _is_allowed(self, frame):
        # Check for allowed op code in the calling frame.
        allowed = [dis.opmap["STORE_ATTR"], dis.opmap["LOAD_CONST"], dis.opmap.get("STOP_CODE", 0)]
        bytecode = frame.f_code.co_code
        instruction = bytecode[frame.f_lasti + 3]
        return instruction in allowed

    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

    @property
    def __dict__(self):  # type:ignore[override]
        # Allow for code completion in a REPL.
        return self.copy()

Functions

__getattr__(attr)

Access the dictionary keys for unknown attributes.

Source code in oct2py/io.py
107
108
109
110
111
112
113
def __getattr__(self, attr):
    """Access the dictionary keys for unknown attributes."""
    try:
        return self[attr]
    except KeyError:
        msg = "'Struct' object has no attribute %s" % attr
        raise AttributeError(msg) from None

__getitem__(attr)

Get a dict value; create a Struct if requesting a Struct member.

Source code in oct2py/io.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def __getitem__(self, attr):
    """Get a dict value; create a Struct if requesting a Struct member."""
    # Do not create a key if the attribute starts with an underscore.
    if attr in self or attr.startswith("_"):
        return dict.__getitem__(self, attr)
    frame = inspect.currentframe()
    if frame is None or frame.f_back is None:
        return None
    # step into the function that called us
    if frame.f_back.f_back and self._is_allowed(frame.f_back.f_back):  # noqa
        dict.__setitem__(self, attr, Struct())
    elif self._is_allowed(frame.f_back):
        dict.__setitem__(self, attr, Struct())
    return dict.__getitem__(self, attr)

Cell

oct2py.Cell

Bases: ndarray

A Python representation of an Octave cell array.

Notes

This class is not meant to be directly created by the user. It is created automatically for cell array values received from Octave. The last axis is squeezed if it is of size 1 to simplify element access.

Examples

from oct2py import octave

generate the struct array

octave.eval("x = cell(2,2); x(:) = 1.0;") x = octave.pull('x') x Cell([[1.0, 1.0], [1.0, 1.0]]) x[0] Cell([1.0, 1.0]) x[0].tolist() [1.0, 1.0]

Source code in oct2py/io.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
class Cell(np.ndarray):
    """A Python representation of an Octave cell array.

    Notes
    =====
    This class is not meant to be directly created by the user.  It is
    created automatically for cell array values received from Octave.
    The last axis is squeezed if it is of size 1 to simplify element access.

    Examples
    ========
    >>> from oct2py import octave
    >>> # generate the struct array
    >>> octave.eval("x = cell(2,2); x(:) = 1.0;")
    >>> x = octave.pull('x')
    >>> x
    Cell([[1.0, 1.0],
           [1.0, 1.0]])
    >>> x[0]
    Cell([1.0, 1.0])
    >>> x[0].tolist()
    [1.0, 1.0]
    """

    def __new__(cls, value, session=None, keep_matlab_shapes=False):
        """Create a cell array from a value and optional Octave session."""
        # Use atleast_2d to preserve Octave size()
        value = np.atleast_2d(np.asarray(value, dtype=object))

        # Extract the values.
        obj = np.empty(value.size, dtype=object).view(cls)
        for i, item in enumerate(value.ravel()):
            obj[i] = _extract(item, session, keep_matlab_shapes)
        obj = obj.reshape(value.shape)
        return obj

    def __repr__(self):
        """A string repr for the cell array."""
        shape = self.shape
        if len(shape) == 1:
            shape = (shape[0], 1)
        msg = self.view(np.ndarray).__repr__()
        msg = msg.replace("array", "Cell", 1)
        return msg.replace(", dtype=object", "", 1)

    def __getitem__(self, key):
        """Get an element of the array."""
        if key == 0 and self.size == 1:
            # Note:
            # Can't use `return super().ravel()[0]` here
            key = tuple([0] * self.ndim)
        return super().__getitem__(key)

Functions

__new__(value, session=None, keep_matlab_shapes=False)

Create a cell array from a value and optional Octave session.

Source code in oct2py/io.py
242
243
244
245
246
247
248
249
250
251
252
def __new__(cls, value, session=None, keep_matlab_shapes=False):
    """Create a cell array from a value and optional Octave session."""
    # Use atleast_2d to preserve Octave size()
    value = np.atleast_2d(np.asarray(value, dtype=object))

    # Extract the values.
    obj = np.empty(value.size, dtype=object).view(cls)
    for i, item in enumerate(value.ravel()):
        obj[i] = _extract(item, session, keep_matlab_shapes)
    obj = obj.reshape(value.shape)
    return obj

__repr__()

A string repr for the cell array.

Source code in oct2py/io.py
254
255
256
257
258
259
260
261
def __repr__(self):
    """A string repr for the cell array."""
    shape = self.shape
    if len(shape) == 1:
        shape = (shape[0], 1)
    msg = self.view(np.ndarray).__repr__()
    msg = msg.replace("array", "Cell", 1)
    return msg.replace(", dtype=object", "", 1)

__getitem__(key)

Get an element of the array.

Source code in oct2py/io.py
263
264
265
266
267
268
269
def __getitem__(self, key):
    """Get an element of the array."""
    if key == 0 and self.size == 1:
        # Note:
        # Can't use `return super().ravel()[0]` here
        key = tuple([0] * self.ndim)
    return super().__getitem__(key)

StructArray

oct2py.StructArray

Bases: recarray

A Python representation of an Octave structure array.

Notes

Accessing a record returns a Cell containing the values. This class is not meant to be directly created by the user. It is created automatically for structure array values received from Octave. The last axis is squeezed if it is of size 1 to simplify element access.

Examples

from oct2py import octave

generate the struct array

octave.eval('x = struct("y", {1, 2}, "z", {3, 4});') x = octave.pull('x') x.y # attribute access -> oct2py Cell Cell([[1.0, 2.0]]) x['z'] # item access -> oct2py Cell Cell([[3.0, 4.0]]) x[0, 0].y # index access, y field 1.0 x[0, 1].z 4.0

Source code in oct2py/io.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
class StructArray(np.recarray):
    """A Python representation of an Octave structure array.

    Notes
    =====
    Accessing a record returns a Cell containing the values.
    This class is not meant to be directly created by the user.  It is
    created automatically for structure array values received from Octave.
    The last axis is squeezed if it is of size 1 to simplify element access.

    Examples
    ========
    >>> from oct2py import octave
    >>> # generate the struct array
    >>> octave.eval('x = struct("y", {1, 2}, "z", {3, 4});')
    >>> x = octave.pull('x')
    >>> x.y  # attribute access -> oct2py Cell
    Cell([[1.0, 2.0]])
    >>> x['z']  # item access -> oct2py Cell
    Cell([[3.0, 4.0]])
    >>> x[0, 0].y  # index access, y field
    1.0
    >>> x[0, 1].z
    4.0
    """

    def __new__(cls, value, session=None, keep_matlab_shapes=False):
        """Create a struct array from a value and optional Octave session."""
        value = np.asarray(value)
        # Squeeze the last element if it is 1
        if value.shape[value.ndim - 1] == 1 and not keep_matlab_shapes:
            value = value.squeeze(axis=value.ndim - 1)
        value = np.atleast_1d(value)

        # Extract the values.
        obj = np.empty(value.size, dtype=value.dtype).view(cls)
        for i, item in enumerate(value.ravel()):
            for name in value.dtype.names:
                obj[i][name] = _extract(item[name], session, keep_matlab_shapes)
        return obj.reshape(value.shape)

    @property
    def fieldnames(self):
        """The field names of the struct array."""
        return self.dtype.names

    def __getattribute__(self, attr):
        """Return object arrays as cells and all other values unchanged."""
        attr = np.recarray.__getattribute__(self, attr)
        if isinstance(attr, np.ndarray) and attr.dtype.kind == "O":
            return Cell(attr)
        return attr

    def __getitem__(self, item):
        """Return object arrays as cells and all other values unchanged."""
        item = np.recarray.__getitem__(self, item)
        if isinstance(item, np.ndarray) and item.dtype.kind == "O":
            return Cell(item)
        return item

    def __repr__(self):
        """A str repr for the struct array."""
        shape = self.shape
        if len(shape) == 1:
            shape = (shape[0], 1)
        msg = "x".join(str(i) for i in shape)
        msg += " StructArray containing the fields:"
        for key in self.fieldnames:
            msg += "\n    %s" % key
        return msg

Attributes

fieldnames property

The field names of the struct array.

Functions

__new__(value, session=None, keep_matlab_shapes=False)

Create a struct array from a value and optional Octave session.

Source code in oct2py/io.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def __new__(cls, value, session=None, keep_matlab_shapes=False):
    """Create a struct array from a value and optional Octave session."""
    value = np.asarray(value)
    # Squeeze the last element if it is 1
    if value.shape[value.ndim - 1] == 1 and not keep_matlab_shapes:
        value = value.squeeze(axis=value.ndim - 1)
    value = np.atleast_1d(value)

    # Extract the values.
    obj = np.empty(value.size, dtype=value.dtype).view(cls)
    for i, item in enumerate(value.ravel()):
        for name in value.dtype.names:
            obj[i][name] = _extract(item[name], session, keep_matlab_shapes)
    return obj.reshape(value.shape)

__getattribute__(attr)

Return object arrays as cells and all other values unchanged.

Source code in oct2py/io.py
192
193
194
195
196
197
def __getattribute__(self, attr):
    """Return object arrays as cells and all other values unchanged."""
    attr = np.recarray.__getattribute__(self, attr)
    if isinstance(attr, np.ndarray) and attr.dtype.kind == "O":
        return Cell(attr)
    return attr

__getitem__(item)

Return object arrays as cells and all other values unchanged.

Source code in oct2py/io.py
199
200
201
202
203
204
def __getitem__(self, item):
    """Return object arrays as cells and all other values unchanged."""
    item = np.recarray.__getitem__(self, item)
    if isinstance(item, np.ndarray) and item.dtype.kind == "O":
        return Cell(item)
    return item

__repr__()

A str repr for the struct array.

Source code in oct2py/io.py
206
207
208
209
210
211
212
213
214
215
def __repr__(self):
    """A str repr for the struct array."""
    shape = self.shape
    if len(shape) == 1:
        shape = (shape[0], 1)
    msg = "x".join(str(i) for i in shape)
    msg += " StructArray containing the fields:"
    for key in self.fieldnames:
        msg += "\n    %s" % key
    return msg

Oct2PyError

oct2py.Oct2PyError

Bases: Exception

Called when we can't open Octave or Octave throws an error

Source code in oct2py/utils.py
12
13
14
15
class Oct2PyError(Exception):
    """Called when we can't open Octave or Octave throws an error"""

    pass

Oct2PyWarning

oct2py.Oct2PyWarning

Bases: UserWarning

Warning raised by oct2py for deprecations and other advisory conditions.

Source code in oct2py/utils.py
18
19
20
21
class Oct2PyWarning(UserWarning):
    """Warning raised by oct2py for deprecations and other advisory conditions."""

    pass

get_log

oct2py.get_log(name=None)

Return a logger for oct2py.

Output may be sent to the logger using the debug, info, warning, error and critical methods.

Parameters:

Name Type Description Default
name str

Name of the log.

None

Returns:

Name Type Description
log object

The logger object.

Source code in oct2py/utils.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def get_log(name=None):
    """Return a logger for oct2py.

    Output may be sent to the logger using the `debug`, `info`, `warning`,
    `error` and `critical` methods.

    Parameters
    ----------
    name : str
        Name of the log.

    Returns
    -------
    log : object
        The logger object.
    """
    name = "oct2py" if name is None else "oct2py." + name
    return logging.getLogger(name)

kill_octave

oct2py.kill_octave()

Kill all octave instances (cross-platform).

This will restart the "octave" instance. If you have instantiated Any other Oct2Py objects, you must restart them.

Source code in oct2py/__init__.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def kill_octave():
    """Kill all octave instances (cross-platform).

    This will restart the "octave" instance.  If you have instantiated
    Any other Oct2Py objects, you must restart them.
    """
    import os  # noqa:PLC0415

    if os.name == "nt":
        os.system("taskkill /im octave /f")  # noqa
    else:
        os.system("killall -9 octave")  # noqa
        os.system("killall -9 octave-cli")  # noqa
    octave.restart()

Oct2PySettings

oct2py.Oct2PySettings

Bases: BaseSettings

Settings for an Oct2Py session.

Can be populated from environment variables (prefixed with OCT2PY_), a .env file, or programmatically.

Attributes:

Name Type Description
model_config SettingsConfigDict

Pydantic-settings configuration: env_prefix="OCT2PY_", populate_by_name=True.

executable (str, optional)

Path to the Octave executable. Resolved in order: this argument, OCTAVE_EXECUTABLE env var, octave/octave-cli on PATH, then Flatpak.

timeout (float, optional)

Timeout in seconds for Octave commands.

oned_as str

If "column", write 1-D numpy arrays as column vectors. If "row" (default), write 1-D numpy arrays as row vectors.

temp_dir (str, optional)

Directory for MAT files.

convert_to_float bool

If True (default), convert integer types to float when passing to Octave.

backend str

The graphics_toolkit to use for plotting. Use "disable" to suppress all figure rendering.

keep_matlab_shapes bool

If True, preserve MATLAB shapes (e.g. scalars as (1,1)).

auto_show (bool, optional)

If True, automatically display figures after each call.

plot_format str

Default format for saved plots (default "svg").

plot_name str

Default base name for saved plots (default "plot").

plot_width (int, optional)

Default plot width in pixels.

plot_height (int, optional)

Default plot height in pixels.

plot_res (int, optional)

Default plot resolution in pixels per inch.

extra_cli_options str

Extra command-line options appended to the Octave invocation.

load_octaverc bool

If True (default), source ~/.octaverc during startup. Set to False to skip loading the user init file, which is useful in reproducible or sandboxed environments where the init file may alter the path, set conflicting options, or is simply unavailable.

ramdisk_size_mb int

macOS only. When set to a positive integer, oct2py will create a temporary HFS+ RAM disk of the given size (in MiB) and use it as the MAT-file exchange directory. The disk is unmounted automatically on session exit. Has no effect on Linux (where /dev/shm is used automatically) or on Windows. Defaults to 0 (disabled). Can also be set via the OCT2PY_RAMDISK_SIZE_MB environment variable.

Examples:

>>> s = Oct2PySettings(backend="disable", timeout=30)
>>> s.backend
'disable'
>>> s.timeout
30.0
Source code in oct2py/settings.py
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
class Oct2PySettings(BaseSettings):
    """Settings for an Oct2Py session.

    Can be populated from environment variables (prefixed with ``OCT2PY_``),
    a ``.env`` file, or programmatically.

    Attributes
    ----------
    model_config : SettingsConfigDict
        Pydantic-settings configuration: ``env_prefix="OCT2PY_"``,
        ``populate_by_name=True``.
    executable : str, optional
        Path to the Octave executable. Resolved in order: this argument,
        ``OCTAVE_EXECUTABLE`` env var, ``octave``/``octave-cli`` on
        ``PATH``, then Flatpak.
    timeout : float, optional
        Timeout in seconds for Octave commands.
    oned_as : str
        If ``"column"``, write 1-D numpy arrays as column vectors.
        If ``"row"`` (default), write 1-D numpy arrays as row vectors.
    temp_dir : str, optional
        Directory for MAT files.
    convert_to_float : bool
        If True (default), convert integer types to float when passing to Octave.
    backend : str
        The graphics_toolkit to use for plotting. Use ``"disable"`` to suppress
        all figure rendering.
    keep_matlab_shapes : bool
        If True, preserve MATLAB shapes (e.g. scalars as (1,1)).
    auto_show : bool, optional
        If True, automatically display figures after each call.
    plot_format : str
        Default format for saved plots (default ``"svg"``).
    plot_name : str
        Default base name for saved plots (default ``"plot"``).
    plot_width : int, optional
        Default plot width in pixels.
    plot_height : int, optional
        Default plot height in pixels.
    plot_res : int, optional
        Default plot resolution in pixels per inch.
    extra_cli_options : str
        Extra command-line options appended to the Octave invocation.
    load_octaverc : bool
        If True (default), source ``~/.octaverc`` during startup.  Set to
        False to skip loading the user init file, which is useful in
        reproducible or sandboxed environments where the init file may
        alter the path, set conflicting options, or is simply unavailable.
    ramdisk_size_mb : int
        macOS only.  When set to a positive integer, oct2py will create a
        temporary HFS+ RAM disk of the given size (in MiB) and use it as
        the MAT-file exchange directory.  The disk is unmounted automatically
        on session exit.  Has no effect on Linux (where ``/dev/shm`` is used
        automatically) or on Windows.  Defaults to ``0`` (disabled).
        Can also be set via the ``OCT2PY_RAMDISK_SIZE_MB`` environment variable.

    Examples
    --------
    >>> s = Oct2PySettings(backend="disable", timeout=30)
    >>> s.backend
    'disable'
    >>> s.timeout
    30.0
    """

    model_config = SettingsConfigDict(
        env_prefix="OCT2PY_",
        populate_by_name=True,
    )

    # Octave executable — reads OCTAVE_EXECUTABLE or OCTAVE env vars
    executable: str | None = Field(
        default=None,
        validation_alias=AliasChoices("OCTAVE_EXECUTABLE", "OCTAVE"),
    )

    # Session settings
    timeout: float | None = None
    oned_as: str = "row"
    temp_dir: str | None = None
    convert_to_float: bool = True
    backend: str = "default"
    keep_matlab_shapes: bool = False
    auto_show: bool | None = None

    # Plot defaults
    plot_format: str = "svg"
    plot_name: str = "plot"
    plot_width: int | None = None
    plot_height: int | None = None
    plot_res: int | None = None
    extra_cli_options: str = ""
    load_octaverc: bool = True
    ramdisk_size_mb: int = 0

configure

oct2py.configure(settings=None, **kwargs)

Configure (or reconfigure) the default oct2py session.

Parameters:

Name Type Description Default
settings Oct2PySettings

Settings object. If not provided, one is built from kwargs and any OCT2PY_* environment variables.

None
**kwargs

Passed directly to Oct2PySettings (e.g. backend="qt", timeout=30).

{}

Examples:

>>> import oct2py
>>> oct2py.configure(backend="disable", timeout=30)
Source code in oct2py/__init__.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def configure(settings=None, **kwargs):
    """Configure (or reconfigure) the default oct2py session.

    Parameters
    ----------
    settings : Oct2PySettings, optional
        Settings object. If not provided, one is built from kwargs and
        any OCT2PY_* environment variables.
    **kwargs
        Passed directly to Oct2PySettings (e.g. ``backend="qt"``,
        ``timeout=30``).

    Examples
    --------
    >>> import oct2py
    >>> oct2py.configure(backend="disable", timeout=30)  # doctest: +SKIP
    """
    global octave  # noqa: PLW0603
    if settings is None:
        settings = Oct2PySettings(**kwargs)
    octave.exit()
    octave = Oct2Py(settings=settings)