首页 > 解决方案 > 如何运行不同的代码取决于从终端或在 IDE 中运行 python 脚本的方式?

问题描述

好的,可以说我有这部分代码(它并不完美)。我想要这种情况 - 我正在检测云名称作为参数,__init__因此所有其他模块和脚本都将在该云上运行,或者如果我想从终端运行特定的 python 文件,我可以检测到我想要的云它要像这样运行python my_script.py cloud1最好的方法是什么?当我使用参数从终端运行以下脚本时,它确实有效,但如果不是,它会给出此错误

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

这是一个代码

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'

我有一个函数可以显示云的 url,它是如何调用的

标签: pythonterminalargparseconfigparser

解决方案


ArgumentParser提供了可选参数,但位置(非标志)参数的默认值是必需的。在这里你可以使用:

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

可能的改进:

在这段代码中,parserargs是类的成员属性。如果它们没有在__init__方法之外使用,它们可能只是本地人:

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

仅识别单个可选参数,argparse可能是矫枉过正。sys.argv可能就足够了:

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

推荐阅读