Coverage for bilby/core/utils/cmd.py: 55%

38 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-06 04:57 +0000

1import argparse 

2import logging 

3import os 

4import subprocess 

5 

6from .log import logger 

7 

8 

9def set_up_command_line_arguments(): 

10 """ Sets up command line arguments that can be used to modify how scripts are run. 

11 

12 Returns 

13 ======= 

14 command_line_args, command_line_parser: tuple 

15 The command_line_args is a Namespace of the command line arguments while 

16 the command_line_parser can be given to a new `argparse.ArgumentParser` 

17 as a parent object from which to inherit. 

18 

19 Notes 

20 ===== 

21 The command line arguments are passed initially at runtime, but this parser 

22 does not have a `--help` option (i.e., the command line options are 

23 available for any script which includes `import bilby`, but no help command 

24 is available. This is done to avoid conflicts with child argparse routines 

25 (see the example below). 

26 

27 Examples 

28 ======== 

29 In the following example we demonstrate how to setup a custom command line for a 

30 project which uses bilby. 

31 

32 .. code-block:: python 

33 

34 # Here we import bilby, which initialises and parses the default command-line args 

35 >>> import bilby 

36 # The command line arguments can then be accessed via 

37 >>> bilby.core.utils.command_line_args 

38 Namespace(clean=False, log_level=20, quite=False) 

39 # Next, we import argparse and define a new argparse object 

40 >>> import argparse 

41 >>> parser = argparse.ArgumentParser(parents=[bilby.core.utils.command_line_parser]) 

42 >>> parser.add_argument('--argument', type=int, default=1) 

43 >>> args = parser.parse_args() 

44 Namespace(clean=False, log_level=20, quite=False, argument=1) 

45 

46 Placing these lines into a script, you'll be able to pass in the usual bilby default 

47 arguments, in addition to `--argument`. To see a list of all options, call the script 

48 with `--help`. 

49 

50 """ 

51 try: 

52 parser = argparse.ArgumentParser( 

53 description="Command line interface for bilby scripts", 

54 add_help=False, allow_abbrev=False) 

55 except TypeError: 

56 parser = argparse.ArgumentParser( 

57 description="Command line interface for bilby scripts", 

58 add_help=False) 

59 parser.add_argument("-v", "--verbose", action="store_true", 

60 help=("Increase output verbosity [logging.DEBUG]." + 

61 " Overridden by script level settings")) 

62 parser.add_argument("-q", "--quiet", action="store_true", 

63 help=("Decrease output verbosity [logging.WARNING]." + 

64 " Overridden by script level settings")) 

65 parser.add_argument("-c", "--clean", action="store_true", 

66 help="Force clean data, never use cached data") 

67 parser.add_argument("-u", "--use-cached", action="store_true", 

68 help="Force cached data and do not check its validity") 

69 parser.add_argument("--sampler-help", nargs='?', default=False, 

70 const='None', help="Print help for given sampler") 

71 parser.add_argument("--bilby-test-mode", action="store_true", 

72 help=("Used for testing only: don't run full PE, but" 

73 " just check nothing breaks")) 

74 parser.add_argument("--bilby-zero-likelihood-mode", action="store_true", 

75 help=("Used for testing only: don't run full PE, but" 

76 " just check nothing breaks")) 

77 args, unknown_args = parser.parse_known_args() 

78 if args.quiet: 

79 args.log_level = logging.WARNING 

80 elif args.verbose: 

81 args.log_level = logging.DEBUG 

82 else: 

83 args.log_level = logging.INFO 

84 

85 return args, parser 

86 

87 

88def run_commandline(cl, log_level=20, raise_error=True, return_output=True): 

89 """Run a string cmd as a subprocess, check for errors and return output. 

90 

91 Parameters 

92 ========== 

93 cl: str 

94 Command to run 

95 log_level: int 

96 See https://docs.python.org/2/library/logging.html#logging-levels, 

97 default is '20' (INFO) 

98 

99 """ 

100 

101 logger.log(log_level, 'Now executing: ' + cl) 

102 if return_output: 

103 try: 

104 out = subprocess.check_output( 

105 cl, stderr=subprocess.STDOUT, shell=True, 

106 universal_newlines=True) 

107 except subprocess.CalledProcessError as e: 

108 logger.log(log_level, 'Execution failed: {}'.format(e.output)) 

109 if raise_error: 

110 raise 

111 else: 

112 out = 0 

113 os.system('\n') 

114 return out 

115 else: 

116 process = subprocess.Popen(cl, shell=True) 

117 process.communicate()