Coverage for ase/cli/parallel.py: 93.55%
31 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1import argparse
2import os
3import runpy
4import sys
7def main(args, parser):
8 from ase.cli.main import CLIError
10 assert 'ase.parallel' not in sys.modules
12 envvar = 'ASE_PARALLEL_WORLD_HOOK'
13 current_hook = os.environ.get(envvar)
14 if current_hook is not None:
15 raise CLIError('Someone already set ASE_PARALLEL_WORLD_HOOK')
17 # As an alternative, we can also start a new Python process
18 # with subprocess.check_call([sys.executable, ...], env=...).
19 os.environ[envvar] = 'ase.hook_mpi4py'
21 if args.script:
22 sys.argv[:] = args.script
23 runpy.run_path(args.script[0], run_name='__main__')
24 elif args.module:
25 sys.argv[:] = args.module
26 runpy.run_module(args.module[0], run_name='__main__')
27 elif args.cmd:
28 eval(compile(args.cmd, '<string>', 'single'))
29 else:
30 raise CLIError('No script, module, or command to run')
33class CLICommand:
34 """Run Python with ASE in parallel using mpi4py.
36 Examples::
38 $ mpiexec -n 4 ase parallel myscript.py --options-to-script
39 $ mpiexec -n 4 python -m ase parallel -m mymodule --options-to-module
40 $ mpiexec -n 4 ase parallel -c "print('hello, world!')"
41 """
43 @staticmethod
44 def add_arguments(parser):
45 group = parser.add_mutually_exclusive_group()
46 parser.add_argument(
47 'script',
48 help='script to run and arguments',
49 nargs=argparse.REMAINDER,
50 )
51 group.add_argument(
52 '-m',
53 '--module',
54 help='module to run and arguments',
55 nargs=argparse.REMAINDER,
56 )
57 group.add_argument(
58 '-c',
59 '--cmd',
60 help='program passed as python string',
61 )
63 @staticmethod
64 def run(args, parser):
65 main(args, parser)