Coverage for ase/cli/exec.py: 93.75%

32 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1# Note: 

2# Try to avoid module level import statements here to reduce 

3# import time during CLI execution 

4 

5 

6class CLICommand: 

7 """Execute code on files. 

8 

9 The given python code is evaluated on the Atoms object read from 

10 the input file for each frame of the file. Either of -e or -E 

11 option should provided for evaluating code given as a string or 

12 from a file, respectively. 

13 

14 Variables which can be used inside the python code: 

15 - `index`: Index of the current Atoms object. 

16 - `atoms`: Current Atoms object. 

17 - `images`: List of all images given as input. 

18 """ 

19 

20 @staticmethod 

21 def add_arguments(parser): 

22 add = parser.add_argument 

23 add('input', nargs='+', metavar='input-file') 

24 add( 

25 '-e', 

26 '--exec-code', 

27 help='Python code to execute on each atoms. The Atoms' 

28 ' object is available as `atoms`. ' 

29 'Example: For printing cell parameters from all the ' 

30 'frames, `print(atoms.cell.cellpar())`', 

31 ) 

32 add( 

33 '-E', 

34 '--exec-file', 

35 help='Python source code file to execute on each ' 

36 'frame, usage is as for -e/--exec-code.', 

37 ) 

38 add( 

39 '-i', 

40 '--input-format', 

41 metavar='FORMAT', 

42 help='Specify input FORMAT', 

43 ) 

44 add( 

45 '-n', 

46 '--image-number', 

47 default=':', 

48 metavar='NUMBER', 

49 help='Pick images from trajectory. NUMBER can be a ' 

50 'single number (use a negative number to count from ' 

51 'the back) or a range: start:stop:step, where the ' 

52 '":step" part can be left out - default values are ' 

53 '0:nimages:1.', 

54 ) 

55 add( 

56 '--read-args', 

57 nargs='+', 

58 action='store', 

59 default={}, 

60 metavar='KEY=VALUE', 

61 help='Additional keyword arguments to pass to `ase.io.read()`.', 

62 ) 

63 

64 @staticmethod 

65 def run(args, parser): 

66 import runpy 

67 

68 from ase.io import read 

69 

70 if not (args.exec_code or args.exec_file): 

71 parser.error("At least one of '-e' or '-E' must be provided") 

72 

73 if args.read_args: 

74 args.read_args = eval('dict({})'.format(', '.join(args.read_args))) 

75 

76 configs = [] 

77 for filename in args.input: 

78 atoms = read( 

79 filename, 

80 args.image_number, 

81 format=args.input_format, 

82 **args.read_args, 

83 ) 

84 if isinstance(atoms, list): 

85 configs.extend(atoms) 

86 else: 

87 configs.append(atoms) 

88 

89 variables = {'images': configs} 

90 for index, atoms in enumerate(configs): 

91 variables['atoms'] = atoms 

92 variables['index'] = index 

93 if args.exec_code: 

94 exec(compile(args.exec_code, '<string>', 'exec'), variables) 

95 if args.exec_file: 

96 runpy.run_path(args.exec_file, init_globals=variables)