【python – 参数化import语句】教程文章相关的互联网学习教程文章

python – 如何通过命令行在pytest中传递参数【代码】

我有一个代码,我需要传递像终端名称这样的参数.这是我的代码以及如何传递参数.我收到一个“文件未找到”的错误,我不明白. 我在终端中尝试了命令:pytest< filename> .py -almonds我应该把这个名字打印成“杏仁”@pytest.mark.parametrize("name") def print_name(name):print ("Displaying name: %s" % name)解决方法:在你的pytest测试中,不要使用@ pytest.mark.parametrize:def test_print_name(name):print ("Displaying name: ...

python – 有没有办法将默认参数设置为等于另一个参数值?【代码】

例如,我有一个基本方法,它将返回一个排列列表.import itertools def perms(elements, set_length=elements):data=[]for x in range(elements):data.append(x+1)return list(itertools.permutations(data, set_length))现在我理解,在当前状态下,这段代码不会运行,因为第二个元素没有定义,但是有没有优雅的方法来完成我在这里尝试做的事情?如果仍然不清楚,我想使默认的setLength值等于传入的第一个参数.谢谢.解决方法:不,函数关键字...

python – 参数内的冒号是什么意思?【代码】

参见英文答案 > What are Type hints in Python 3.5 3个在words_pron_dict:str上的冒号是什么意思?我在python 2.7上遇到语法错误.是python 3吗?我怎么用呢?class TextToSpeech:CHUNK = 1024def __init__(self, words_pron_dict:str = 'cmudict-0.7b.txt'):self._l = {}self._load_words(words_pron_dict)解决方法:这是一个类型注释:https://docs.python.org/3/library/typing.html 你应该...

为什么使用`arg = None`修复Python的可变默认参数问题?【代码】

我正在学习Python,我正在处理the Mutable Default Argument problem.# BAD: if `a_list` is not passed in, the default will wrongly retain its contents between successive function calls def bad_append(new_item, a_list=[]):a_list.append(new_item)return a_list# GOOD: if `a_list` is not passed in, the default will always correctly be [] def good_append(new_item, a_list=None):if a_list is None:a_list = []a_...

lambda函数不关闭Python中的参数?【代码】

代码说明更多:from pprint import pprintli = []for i in range(5):li.append(lambda : pprint(i))for k in li:k()让:4 4 4 4 4为什么不0 1 2 3 4?? 谢谢. 附:如果我编写完整的装饰器,它按预期工作:from pprint import pprintli = []#for i in range(5):#li.append(lambda : pprint(i))def closure(i):def _func():pprint(i)return _funcfor i in range(5):li.append(closure(i))for k in li:k()解决方法:你需要做的:lambda i...

python – 将表名作为参数传递给psycopg2【代码】

我有以下代码,使用pscyopg2:sql = 'select %s from %s where utctime > %s and utctime < %s order by utctime asc;' data = (dataItems, voyage, dateRangeLower, dateRangeUpper) rows = cur.mogrify(sql, data)这输出:select 'waterTemp, airTemp, utctime' from 'ss2012_t02' where utctime > '2012-05-03T17:01:35+00:00'::timestamptz and utctime < '2012-05-01T17:01:35+00:00'::timestamptz order by utctime asc;当我执...

python – 使用类作为其方法中参数的类型提示【代码】

我在下面包含的代码会引发以下错误:NameError: name 'Vector2' is not defined 在这一行:def Translate (self, pos: Vector2):为什么Python无法在Translate方法中识别我的Vector2类?class Vector2:def __init__(self, x: float, y: float):self.x = xself.y = ydef Translate(self, pos: Vector2):self.x += pos.xself.y += pos.y解决方法:因为当遇到Translate(在编译类主体时),Vector2尚未定义(它当前正在编译,尚未执行名称绑定...

python 中的位置参数和默认参数

原文链接:https://blog.csdn.net/keycoder/article/details/79469222args与位置参数和默认参数混用的情况下 示例一、(三者顺序是:位置参数、默认参数、*args)(注意三者的顺序) *args:(表示参数元组) def foo(x,y=1,*args): pass foo (1,2,3,4,5) // 其中的x为1,y=1的值被2替换,3,4,5都给args,即args=(3,4,5) 1 2 3 4 示例二、(三者顺序是:位置参数、*args、默认参数) def foo(x,*args,y=1): pass foo (1,2,3...

在Python中打印多个参数【代码】

这只是我的代码片段:print("Total score for %s is %s ", name, score)但我希望它打印出来:“Total score for (name) is (score)”其中name是列表中的变量,score是整数.这是Python 3.3,如果这有帮助的话.解决方法:有很多方法可以做到这一点.要使用%-formatting修复当前代码,您需要传入一个元组: >将其作为元组传递:print("Total score for %s is %s" % (name, score))具有单个元素的元组看起来像(‘this’,). 以下是一些其他...

python – 解析命令行参数的最佳方法是什么?【代码】

解析Python命令行参数的最简单,最简洁,最灵活的方法或库是什么?解决方法:这个答案表明optparse适用于较旧的Python版本.对于Python 2.7及更高版本,argparse取代了optparse.有关更多信息,请参见this answer. 正如其他人所指出的那样,你最好选择optparse而不是getopt. getopt几乎是标准getopt(3)C库函数的一对一映射,并不是很容易使用. optparse虽然有点冗长,但结构更好,后期更容易扩展. 这是向解析器添加选项的典型行:parser.add_o...

python – 简单的argparse示例通缉:1个参数,3个结果【代码】

argparse python module的documentation虽然非常出色,但我确信,对于我的小初学者大脑来说,这对我来说太过分了.我不需要在命令行上进行数学运算,也不需要在屏幕上使用格式化线条或更改选项字符.我想要做的就是“如果arg是A,那么,如果B这样做,如果以上都不显示帮助并退出”.解决方法:我对原始问题的理解是双重的.首先,就最简单的argparse示例而言,我很惊讶我在这里没有看到它.当然,简单来说,它也是所有开销,但功率很小,但它可能会让你...

python – 使用多个__init__参数对元组进行子类化【代码】

以下代码有效:class Foo(tuple):def __init__(self, b):super(Foo, self).__init__(tuple(b))if __name__ == '__main__':print Foo([3, 4])$python play.py 结果:play.py:4: DeprecationWarning: object.__init__() takes no parameterssuper(Foo, self).__init__(tuple(b)) (3, 4)但不是以下内容:class Foo(tuple):def __init__(self, a, b):super(Foo, self).__init__(tuple(b))if __name__ == '__main__':print Foo(None, [3...

在Python中获取方法参数名称【代码】

鉴于Python函数:def aMethod(arg1, arg2):pass如何提取参数的数量和名称.即,鉴于我有一个func的引用,我想要返回func.[something](“arg1”,“arg2”). 这种情况的使用场景是我有一个装饰器,我希望使用方法参数的顺序与它们为实际函数出现的顺序相同.即,当我调用aMethod(“a”,“b”)时,装饰器看起来如何打印“a,b”?解决方法:看看inspect模块 – 这将为您检查各种代码对象属性.>>> inspect.getfullargspec(aMethod) (['arg1', 'a...

你如何在python中生成动态(参数化)单元测试?【代码】

我有一些测试数据,想为每个项目创建一个单元测试.我的第一个想法是这样做:import unittestl = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]class TestSequence(unittest.TestCase):def testsample(self):for name, a,b in l:print "test", nameself.assertEqual(a,b)if __name__ == '__main__':unittest.main()这样做的缺点是它在一次测试中处理所有数据.我想在运行中为每个项目生成一个测试.有什么建议?解决方法...

python – 用户输入和命令行参数【代码】

我如何拥有a)可以接受用户输入的Python脚本以及如何创建它b)如果从命令行运行,则读入参数?解决方法:要读取用户输入,您可以尝试使用the cmd module轻松创建一个迷你命令行解释器(带有帮助文本和自动完成)和raw_input(用于Python 3的input),以便从用户那里读取一行文本.text = raw_input("prompt") # Python 2 text = input("prompt") # Python 3命令行输入在sys.argv中.在你的脚本中尝试这个:import sys print (sys.argv)解析命...

IMPORT - 相关标签
参数化 - 相关标签