Search code examples
pythonterminalargparseconfigparser

How to run different code depends on the way python script is runned from the terminal or in an IDE?


Ok, so lets say I have this part of the code (it is not perfect). I want this scenario - I am detecting the cloud name ones as an argument in __init__ so all other modules and scripts will run on that cloud, or if I want to run the specific python file from the terminal I can detect the cloud on which I want it to be runned like this python my_script.py cloud1 What would be the best way to do this? The following script does work when I am running it from the terminal with the argument, but if not it gives this error

usage: To check what is the cloud name config_parser.py: error: too few arguments'

here is a code

class CredentialsCP:

def __init__(self, cloud_name=None):
    self.config = ConfigParser.ConfigParser()
    self.cloud_name = cloud_name
    self.config_file_pass = os.path.expanduser('~/PycharmProjects/ui/config.cfg')
    self.parser = ArgumentParser(usage='To check what is the cloud name')
    self.parser.add_argument('cloud')
    self.args = self.parser.parse_args()
    if self.args:
        self.cloud_name = self.args.cloud
    if self.cloud_name is None:
        self.cloud_name = 'cloud1'

I have a function that shows a url of the cloud, that how it is callable


Solution

  • ArgumentParser has provision for optional arguments, but the default for positional (non flag) arguments is required. Here you could use:

    self.parser = ArgumentParser(usage='To check what is the cloud name')
    self.parser.add_argument('cloud', nargs='?', default='cloud1') # optional argument with default value
    self.args = self.parser.parse_args()
    self.cloud_name = self.args.cloud
    

    Possible improvements:

    In this code, parser and args are member attributes of the class. If they are not used outside the __init__ method, they could just be locals:

    self.parser = ArgumentParser(usage='To check what is the cloud name')
    parser.add_argument('cloud', nargs='?', default='cloud1') # optional argument with default value
    args = .parser.parse_args()
    self.cloud_name = args.cloud
    

    For only identifying a single optional argument, argparse may be overkill. sys.argv could be enough:

    ...
    self.config_file_pass = os.path.expanduser('~/PycharmProjects/ui/config.cfg')
    self.cloud_name = sys.argv[1] if len(sys.argv) > 1 else 'cloud1'