Questions tagged «python»

Python是一种多范式,动态类型的多用途编程语言。它旨在快速学习,理解和使用并强制使用干净统一的语法。请注意,Python 2自2020年1月1日起已不再受支持。不过,对于特定于版本的Python问题,请添加[python-2.7]或[python-3.x]标签。使用Python变体或库(例如Jython,PyPy,Pandas,Numpy)时,请将其包含在标签中。


6
在Python脚本中执行curl命令
我正在尝试在python脚本中执行curl命令。 如果我在终端中执行此操作,则如下所示: curl -X POST -d '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001 我看到了使用建议pycurl,但是我不知道如何将其应用于我的。 我尝试使用: subprocess.call([ 'curl', '-X', 'POST', '-d', flow_x, 'http://localhost:8080/firewall/rules/0000000000000001' ]) 可以,但是还有更好的方法吗?
72 python  curl  pycurl 

5
Python Pandas复制数据框中的行
如果数据如下所示: Store,Dept,Date,Weekly_Sales,IsHoliday 1,1,2010-02-05,24924.5,FALSE 1,1,2010-02-12,46039.49,TRUE 1,1,2010-02-19,41595.55,FALSE 1,1,2010-02-26,19403.54,FALSE 1,1,2010-03-05,21827.9,FALSE 1,1,2010-03-12,21043.39,FALSE 1,1,2010-03-19,22136.64,FALSE 1,1,2010-03-26,26229.21,FALSE 1,1,2010-04-02,57258.43,FALSE 我想复制IsHoliday等于TRUE的行,我可以这样做: is_hol = df['IsHoliday'] == True df_try = df[is_hol] df=df.append(df_try*10) 但是是否有更好的方法来执行此操作,因为我需要将假日行重复5次,如果使用上述方法,则必须追加5次。


3
如何在Python中使用subprocess.check_output()?
我找到了有关subprocess.check_output()的文档,但是找不到带有参数的文档,而且该文档也不是很深入。我正在使用Python 3(但试图通过Python 3运行Python 2文件) 我正在尝试运行以下命令: python py2.py -i test.txt -i是argparse的位置参数,test.txt是-i,py2.py是要运行的文件 我尝试了很多(无效)变体,包括: py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt']) py2output = subprocess.check_output([str('python'),'py2.py','-i', test.txt'])


3
在Python中断言变量类型的正确方法
在使用函数时,我希望确保变量的类型符合预期。怎么做对? 这是一个伪函数示例,尝试在继续其作用之前执行此操作: def my_print(begin, text, end): """Print 'text' in UPPER between 'begin' and 'end' in lower """ for i in (begin, text, end): assert isinstance(i, str), "Input variables should be strings" out = begin.lower() + text.upper() + end.lower() print out def test(): """Put your test cases here! """ assert my_print("asdf", …
72 python  testing  assert 


4
如何在OpenCV(Python)中将灰度图像转换为RGB?
我正在学习使用OpenCV进行实时应用程序的图像处理。我对图像进行了一些阈值处理,并希望将轮廓标记为绿色,但是由于我的图像是黑白图像,所以它们没有显示为绿色。 在程序的早期,我曾经gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)将RGB转换为灰度,但是回过头来,我很困惑,该函数backtorgb = cv2.cvtColor(gray,cv2.CV_GRAY2RGB)给出了: AttributeError:“模块”对象没有属性“ CV_GRAY2RGB”。 下面的代码似乎不是用绿色绘制轮廓。这是因为它是灰度图像吗?如果是这样,我可以将灰度图像转换回RGB,以绿色显示轮廓吗? import numpy as np import cv2 import time cap = cv2.VideoCapture(0) while(cap.isOpened()): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) ret, gb = cv2.threshold(gray,128,255,cv2.THRESH_BINARY) gb = cv2.bitwise_not(gb) contour,hier = cv2.findContours(gb,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE) for cnt in contour: cv2.drawContours(gb,[cnt],0,255,-1) gray = cv2.bitwise_not(gb) cv2.drawContours(gray,contour,-1,(0,255,0),3) cv2.imshow('test', …

11
如何使用xml.etree.ElementTree编写XML声明
我正在使用Python在Python中生成XML文档ElementTree,但是在转换为纯文本时,该tostring函数不包含XML声明。 from xml.etree.ElementTree import Element, tostring document = Element('outer') node = SubElement(document, 'inner') node.NewValue = 1 print tostring(document) # Outputs "<outer><inner /></outer>" 我需要我的字符串包含以下XML声明: <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 但是,似乎没有任何记录的方式来执行此操作。 有没有合适的方法来呈现XML声明ElementTree?

20
在Python中截断为三个小数
我如何获得1324343032.324? 如您在下面看到的,以下内容不起作用: >>1324343032.324325235 * 1000 / 1000 1324343032.3243253 >>int(1324343032.324325235 * 1000) / 1000.0 1324343032.3239999 >>round(int(1324343032.324325235 * 1000) / 1000.0,3) 1324343032.3239999 >>str(1324343032.3239999) '1324343032.32'
72 python 

1
为什么下一个为什么会引发“ StopIteration”,而“ for”却会正常返回?
在这段代码中,为什么使用for结果为noStopIteration 或for循环捕获所有异常然后静默退出?在这种情况下,为什么会有多余的return?还是由以下 raise StopIteration原因引起的return None? #!/usr/bin/python3.1 def countdown(n): print("counting down") while n >= 9: yield n n -= 1 return for x in countdown(10): print(x) c = countdown(10) next(c) next(c) next(c) 假设StopIteration由触发return None。什么时候GeneratorExit产生的? def countdown(n): print("Counting down from %d" % n) try: while n > 0: yield n n = …


5
Django post_save()信号实现
我有一个关于django的问题。 我这里有许多对多模型 class Product(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(default=0.0, max_digits=9, decimal_places=2) stock = models.IntegerField(default=0) def __unicode__(self): return self.name class Cart(models.Model): customer = models.ForeignKey(Customer) products = models.ManyToManyField(Product, through='TransactionDetail') t_date = models.DateField(default=datetime.now()) t_sum = models.FloatField(default=0.0) def __unicode__(self): return str(self.id) class TransactionDetail(models.Model): product = models.ForeignKey(Product) cart = models.ForeignKey(Cart) amount = models.IntegerField(default=0) 对于创建的1个购物车对象,我可以插入尽可能多的新TransactionDetail对象(产品和金额)。我的问题是。如何实现触发器?我想要的是每当创建交易明细时,我希望产品的存货数量减去交易明细中的数量。 …

6
运行py.test时出现错误ImportMismatchError
当我在本地运行测试时,它可以正常工作,但是在创建docker并在容器内运行后,我遇到了错误。 /usr/local/lib/python3.5/site-packages/_pytest/config.py:325: in _getconftestmodules return self._path2confmods[path] E KeyError: local('/apis/db/tests') During handling of the above exception, another exception occurred: /usr/local/lib/python3.5/site-packages/_pytest/config.py:356: in _importconftest return self._conftestpath2mod[conftestpath] E KeyError: local('/apis/db/tests/conftest.py') During handling of the above exception, another exception occurred: /usr/local/lib/python3.5/site-packages/_pytest/config.py:362: in _importconftest mod = conftestpath.pyimport() /usr/local/lib/python3.5/site-packages/py/_path/local.py:680: in pyimport raise self.ImportMismatchError(modname, modfile, self) _pytest.config.ConftestImportFailure: ImportMismatchError('conftest', …
72 python  docker  pytest 

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.