Skip to content

Commit 1bb285c

Browse files
authored
Merge branch 'master' into fix/numeric-attribute-byte-order
2 parents 84972a6 + f609107 commit 1bb285c

3 files changed

Lines changed: 107 additions & 25 deletions

File tree

‎Changelog‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
version 1.7.4.1 (tag v1.7.4.1rel)
22
=================================
33
* Convert non-native-endian numeric attributes to native byte order before writing (issue #1502).
4+
* Fix command-line usage error exit codes and --help handling, honour nc4tonc3 --chunk,
5+
and fix ncinfo group dimension selection (issue #1500).
46
* Change default encoding for stringtochar/chartostring functions from 'utf-8' to 'utf-8'/'ascii' for dtype.kind='U'/'S'
57
(issue #1464).
68
* Fix DeprecationWarning for assigning to numpy.ndarray.shape for numpy >= 2.5.0 (issue #1468).

‎src/netCDF4/utils.py‎

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -514,14 +514,14 @@ def ncinfo():
514514

515515
try:
516516
opts, pargs = getopt.getopt(sys.argv[1:],'hv:g:d:',
517-
['group=',
517+
['help',
518+
'group=',
518519
'variable=',
519520
'dimension='])
520-
except:
521-
(type, value, traceback) = sys.exc_info()
522-
sys.stdout.write("Error parsing the options. The error was: %s\n" % value)
521+
except getopt.GetoptError as error:
522+
sys.stdout.write("Error parsing the options. The error was: %s\n" % error)
523523
sys.stderr.write(usage)
524-
sys.exit(0)
524+
sys.exit(2)
525525

526526
# Get the options
527527
group = None; var = None; dim=None
@@ -538,15 +538,15 @@ def ncinfo():
538538
else:
539539
sys.stdout.write("%s: Unrecognized option\n" % option[0])
540540
sys.stderr.write(usage)
541-
sys.exit(0)
541+
sys.exit(2)
542542

543543
# filename passed as last argument
544544
try:
545545
filename = pargs[-1]
546546
except IndexError:
547547
sys.stdout.write("You need to pass netcdf filename!\n.")
548548
sys.stderr.write(usage)
549-
sys.exit(0)
549+
sys.exit(2)
550550

551551
f = Dataset(filename)
552552
if group is None:
@@ -565,7 +565,7 @@ def ncinfo():
565565
if var is not None:
566566
print(g.variables[var])
567567
if dim is not None:
568-
print(g.dimensions[var])
568+
print(g.dimensions[dim])
569569
f.close()
570570

571571
def _nc4tonc3(filename4,filename3,clobber=False,nchunk=10,quiet=False,format='NETCDF3_64BIT'):
@@ -653,16 +653,15 @@ def nc4tonc3():
653653

654654
try:
655655
opts, pargs = getopt.getopt(sys.argv[1:], 'ho',
656-
['format=','chunk=','quiet='])
657-
except:
658-
(type, value, traceback) = sys.exc_info()
659-
sys.stdout.write("Error parsing the options. The error was: %s\n" % value)
656+
['help','format=','chunk=','quiet='])
657+
except getopt.GetoptError as error:
658+
sys.stdout.write("Error parsing the options. The error was: %s\n" % error)
660659
sys.stderr.write(usage)
661-
sys.exit(0)
660+
sys.exit(2)
662661

663662
# default options
664663
quiet = 0
665-
chunk = 1000
664+
chunk = 10
666665
format = 'NETCDF3_64BIT'
667666
overwritefile = 0
668667

@@ -680,22 +679,22 @@ def nc4tonc3():
680679
elif option[0] == '--chunk':
681680
chunk = int(option[1])
682681
else:
683-
sys.stdout.write("%s : Unrecognized option\n" % options[0])
682+
sys.stdout.write("%s : Unrecognized option\n" % option[0])
684683
sys.stderr.write(usage)
685-
sys.exit(0)
684+
sys.exit(2)
686685

687686
# if we pass a number of files different from 2, abort
688687
if len(pargs) < 2 or len(pargs) > 2:
689688
sys.stdout.write("You need to pass both source and destination!\n.")
690689
sys.stderr.write(usage)
691-
sys.exit(0)
690+
sys.exit(2)
692691

693692
# Catch the files passed as the last arguments
694693
filename4 = pargs[0]
695694
filename3 = pargs[1]
696695

697696
# copy the data from filename4 to filename3.
698-
_nc4tonc3(filename4,filename3,clobber=overwritefile,quiet=quiet,format=format)
697+
_nc4tonc3(filename4,filename3,clobber=overwritefile,nchunk=chunk,quiet=quiet,format=format)
699698

700699

701700
def _nc3tonc4(filename3,filename4,unpackshort=True,
@@ -856,7 +855,8 @@ def nc3tonc4():
856855

857856
try:
858857
opts, pargs = getopt.getopt(sys.argv[1:], 'ho',
859-
['classic=',
858+
['help',
859+
'classic=',
860860
'vars=',
861861
'zlib=',
862862
'quiet=',
@@ -868,11 +868,10 @@ def nc3tonc4():
868868
'chunk=',
869869
'istart=',
870870
'istop='])
871-
except:
872-
(type, value, traceback) = sys.exc_info()
873-
sys.stdout.write("Error parsing the options. The error was: %s\n" % value)
871+
except getopt.GetoptError as error:
872+
sys.stdout.write("Error parsing the options. The error was: %s\n" % error)
874873
sys.stderr.write(usage)
875-
sys.exit(0)
874+
sys.exit(2)
876875

877876
# default options
878877
overwritefile = 0
@@ -923,13 +922,13 @@ def nc3tonc4():
923922
else:
924923
sys.stdout.write("%s: Unrecognized option\n" % option[0])
925924
sys.stderr.write(usage)
926-
sys.exit(0)
925+
sys.exit(2)
927926

928927
# if we pass a number of files different from 2, abort
929928
if len(pargs) < 2 or len(pargs) > 2:
930929
sys.stdout.write("You need to pass both source and destination!.\n")
931930
sys.stderr.write(usage)
932-
sys.exit(0)
931+
sys.exit(2)
933932

934933
# Catch the files passed as the last arguments
935934
filename3 = pargs[0]

‎test/test_cli.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import sys
2+
from unittest.mock import patch
3+
4+
import numpy as np
5+
import pytest
6+
7+
from netCDF4 import Dataset, utils
8+
9+
10+
@pytest.mark.parametrize("command", [utils.ncinfo, utils.nc3tonc4, utils.nc4tonc3])
11+
@pytest.mark.parametrize("args", [[], ["--unknown"]])
12+
def test_usage_error(command, args, monkeypatch, capsys):
13+
monkeypatch.setattr(sys, "argv", [command.__name__, *args])
14+
with pytest.raises(SystemExit) as exc:
15+
command()
16+
assert exc.value.code == 2
17+
assert "usage:" in capsys.readouterr().err
18+
19+
20+
@pytest.mark.parametrize("command, option", [
21+
(utils.ncinfo, "--group"),
22+
(utils.nc3tonc4, "--chunk"),
23+
(utils.nc4tonc3, "--chunk"),
24+
])
25+
def test_missing_option_value(command, option, monkeypatch, capsys):
26+
monkeypatch.setattr(sys, "argv", [command.__name__, option])
27+
with pytest.raises(SystemExit) as exc:
28+
command()
29+
assert exc.value.code == 2
30+
assert "usage:" in capsys.readouterr().err
31+
32+
33+
@pytest.mark.parametrize("command", [utils.nc3tonc4, utils.nc4tonc3])
34+
@pytest.mark.parametrize("args", [["source.nc"], ["source.nc", "dest.nc", "extra.nc"]])
35+
def test_converter_file_count(command, args, monkeypatch, capsys):
36+
monkeypatch.setattr(sys, "argv", [command.__name__, *args])
37+
with pytest.raises(SystemExit) as exc:
38+
command()
39+
assert exc.value.code == 2
40+
assert "usage:" in capsys.readouterr().err
41+
42+
43+
@pytest.mark.parametrize("command", [utils.ncinfo, utils.nc3tonc4, utils.nc4tonc3])
44+
@pytest.mark.parametrize("option", ["-h", "--help"])
45+
def test_help(command, option, monkeypatch, capsys):
46+
monkeypatch.setattr(sys, "argv", [command.__name__, option])
47+
with pytest.raises(SystemExit) as exc:
48+
command()
49+
assert exc.value.code == 0
50+
output = capsys.readouterr()
51+
assert "usage:" in output.err
52+
assert "Error" not in output.out
53+
54+
55+
def test_ncinfo_group_dimension(tmp_path, monkeypatch, capsys):
56+
filename = str(tmp_path / "groups.nc")
57+
with Dataset(filename, "w") as dataset:
58+
dataset.createGroup("g1").createDimension("x", 7)
59+
monkeypatch.setattr(sys, "argv", ["ncinfo", "-g", "g1", "-d", "x", filename])
60+
utils.ncinfo()
61+
assert "name = 'x', size = 7" in capsys.readouterr().out
62+
63+
64+
@pytest.mark.parametrize("chunk", [None, 0, 5])
65+
def test_nc4tonc3_chunk(tmp_path, chunk, monkeypatch):
66+
source = str(tmp_path / "source.nc")
67+
destination = str(tmp_path / "destination.nc")
68+
values = np.arange(25, dtype="i4")
69+
with Dataset(source, "w", format="NETCDF4_CLASSIC") as dataset:
70+
dataset.createDimension("record", None)
71+
dataset.createVariable("values", "i4", ("record",))[:] = values
72+
args = ["nc4tonc3", "--quiet=1"]
73+
if chunk is not None:
74+
args.append("--chunk=%s" % chunk)
75+
monkeypatch.setattr(sys, "argv", [*args, source, destination])
76+
with patch.object(utils, "_nc4tonc3", wraps=utils._nc4tonc3) as convert:
77+
utils.nc4tonc3()
78+
assert convert.call_args.kwargs["nchunk"] == (10 if chunk is None else chunk)
79+
with Dataset(destination) as dataset:
80+
assert dataset.file_format == "NETCDF3_64BIT_OFFSET"
81+
np.testing.assert_array_equal(dataset.variables["values"][:], values)

0 commit comments

Comments
 (0)