python - 如何运行不同的代码取决于从终端或在 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,它是如何调用的
解决方案
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
可能的改进:
在这段代码中,parser
和args
是类的成员属性。如果它们没有在__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'
推荐阅读
- android - 将地图存储在房间数据库中
- c# - 在 WPF 中,当我按下按钮时,会执行另一个事件按钮
- gcc - 显示编译过程的标志
- c - C中的Shell程序如何运行子目录中的已编译程序?
- debugging - 在没有警告/同意的情况下自动添加代码行
- haskell - 如何将重叠编译指示应用于派生实例
- python - 你好,我是learnign pyton,我得到一个错误响应400,我在谷歌上搜索解决方案,但我没有找到
- c# - 如何修复未显示的 Visual Studio C# 项目属性?
- xml - Angular 11文件上传formdata到asp.net核心api为空
- azure - Azure 自动化帐户中的 Runbook 和变量数是否有限制?