有没有办法,例如,Hello World!每n秒打印一次?例如,程序将通过我拥有的任何代码,然后一旦它有5秒(有time.sleep())它将执行该代码.我会使用它来更新文件,而不是打印Hello World.
例如:
startrepeat("print('Hello World')", .01) # Repeats print('Hello World') ever .01 seconds
for i in range(5):
print(i)
>> Hello World!
>> 0
>> 1
>> 2
>> Hello World!
>> 3
>> Hello World!
>> 4
Run Code Online (Sandbox Code Playgroud) 在django中如何检查查询是否存在任何条目
sc=scorm.objects.filter(Header__id=qp.id)
Run Code Online (Sandbox Code Playgroud)
这就是它在php中的表现
if(mysql_num_rows($resultn)) {
// True condition
}
else {
// False condition
}
Run Code Online (Sandbox Code Playgroud) 我有一个代码,我尝试访问资源,但有时它不可用,并导致异常.我尝试使用上下文管理器实现重试引擎,但我无法处理__enter__上下文表单上下文管理器中调用者引发的异常.
class retry(object):
def __init__(self, retries=0):
self.retries = retries
self.attempts = 0
def __enter__(self):
for _ in range(self.retries):
try:
self.attempts += 1
return self
except Exception as e:
err = e
def __exit__(self, exc_type, exc_val, traceback):
print 'Attempts', self.attempts
Run Code Online (Sandbox Code Playgroud)
这是一些只引发异常的例子(我希望处理的那个)
>>> with retry(retries=3):
... print ok
...
Attempts 1
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'ok' is not defined
>>>
>>> with retry(retries=3):
... open('/file')
...
Attempts 1
Traceback …Run Code Online (Sandbox Code Playgroud) 我想从现在到2010年8月之间获得所有月份,因为列表格式如下:
['2010-08-01', '2010-09-01', .... , '2016-02-01']
Run Code Online (Sandbox Code Playgroud)
现在这就是我所拥有的:
months = []
for y in range(2010, 2016):
for m in range(1, 13):
if (y == 2010) and m < 8:
continue
if (y == 2016) and m > 2:
continue
month = '%s-%s-01' % (y, ('0%s' % (m)) if m < 10 else m)
months.append(month)
Run Code Online (Sandbox Code Playgroud)
什么是更好的方法来做到这一点?
我对这个问题有些困难.我需要删除包含在波浪括号中的所有数据.
像这样:
Hello {{world of the {{ crazy}} {{need {{ be}}}} sea }} there.
Run Code Online (Sandbox Code Playgroud)
变为:
Hello there.
Run Code Online (Sandbox Code Playgroud)
这是我的第一次尝试(我知道这很糟糕):
while 1:
firstStartBracket = text.find('{{')
if (firstStartBracket == -1):
break;
firstEndBracket = text.find('}}')
if (firstEndBracket == -1):
break;
secondStartBracket = text.find('{{',firstStartBracket+2);
lastEndBracket = firstEndBracket;
if (secondStartBracket == -1 or secondStartBracket > firstEndBracket):
text = text[:firstStartBracket] + text[lastEndBracket+2:];
continue;
innerBrackets = 2;
position = secondStartBracket;
while innerBrackets:
print innerBrackets;
#everytime we find a next start bracket before the ending add 1 to inner …Run Code Online (Sandbox Code Playgroud) 当减去两个datetime对象时,我理解结果是timedelta对象:
import datetime
AcDepart = 1900-01-01 18:00:00
AcArrival = 1900-01-01 07:00:00
ActualHours = AcDepart - AcArrival
Run Code Online (Sandbox Code Playgroud)
然后我想从中减去两个其他date time对象的总和ActualHours
这是另外两个对象:
HrsEarly = 1900-01-01 02:00:00
HrsLate = 1900-01-01 00:30:00
Run Code Online (Sandbox Code Playgroud)
这是无法完成的等式:
UnCalcTime = ActualHours - (HrsEarly + HrsLate)
Run Code Online (Sandbox Code Playgroud)
这是错误:
UnCalcTime = ActualHours - (HrsEarly + HrsLate)
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
Run Code Online (Sandbox Code Playgroud)
所以,我显然不能添加datetime.datetime. 有谁知道我怎么能解决这个问题?可以timedelta加在一起吗?如果是这样,我该如何转换datetime为timedelta?
任何帮助将不胜感激,因为我一直试图解决这个问题很长时间没有成功。
我必须创建一个函数,它接受一个参数字,并返回文本中单词之前的单词的平均长度(以字符为单位).如果单词恰好是文本中出现的第一个单词,则该单词的前一个单词的长度应为零.例如
>>> average_length("the")
4.4
>>> average_length('whale')
False
average_length('ship.')
3.0
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止所写的,
def average_length(word):
text = "Call me Ishmael. Some years ago - never mind how long..........."
words = text.split()
wordCount = len(words)
Sum = 0
for word in words:
ch = len(word)
Sum = Sum + ch
avg = Sum/wordCount
return avg
Run Code Online (Sandbox Code Playgroud)
我知道这根本不对,但是我无法正确处理这个问题.这个问题要求我在文本中找到单词的每个实例,当你这样做时,计算文本中紧接在它之前的单词的长度.不是每个单词从开头到那个单词,只有一个.
我还应该提到所有的测试只会使用'Moby Dick'中的第一段来测试我的代码:
"叫我以实玛利.几年前 - 没关系多长时间 - 我的钱包里没有钱,也没有什么特别令我感兴趣的,我觉得我会稍微航行一下,看看这个世界的水域.这是我驱除脾脏和调节血液循环的一种方式.每当我发现自己的嘴巴变得严峻;每当我的灵魂中充满潮湿,毛躁的十一月;每当我发现自己在棺材仓库前不由自主地停顿,并带来在我遇到的每一次葬礼的后方;特别是每当我的hypos得到我这样的优势时,它需要一个强有力的道德原则来防止我故意踩到街上,并有条不紊地敲掉别人的帽子 - 然后,我说我是时候尽快出海了.这是我用手枪和球的替代品.随着哲学的蓬勃发展,卡托把自己扔在剑上;我悄悄地带上了船.这里没有什么令人惊讶的.知道了,等等 大多数所有男性,无论是时间还是其他人,都非常珍惜和我一样对待海洋的感情."
我仍然是python的新手,所以请多多包涵,所以我试图用编写脚本,python2-pyserial但是我一直收到错误消息。Attempting to use a port that is not open这是脚本:
#!/usr/bin/python
import serial, time
#initialization and open the port
#possible timeout values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
ser.port = "/dev/ttyUSB2"
ser.baudrate = 115200
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试用例来模拟 api 调用,并使用 python 响应来模拟 api 调用。
下面是我的模拟,
with responses.RequestsMock() as rsps:
url_re = re.compile(r'.*udemy.com/api-2.0/courses.*')
url_re = re.compile(r'https://www.udemy.com/api-2.0/courses')
rsps.add(
responses.GET, url_re,
body=mocked_good_json,
status=200,
content_type='application/json',
match_querystring=True
)
courses = self.app.courses.get_all(page=1, page_size=2)
for course in courses:
self.assertTrue(isinstance(course, Course))
self.assertTrue(hasattr(course, 'id'))
self.assertTrue(hasattr(course, 'title'))
self.assertIsNotNone(course.id)
Run Code Online (Sandbox Code Playgroud)
当我执行这个模拟时,我收到此错误 -
AssertionError: Not all requests have been executed [(u'GET', 'https://www.udemy.com/api-2.0/courses/')]
Run Code Online (Sandbox Code Playgroud)
当我删除mock并直接调用api时,它工作正常。
关于我的模拟失败的原因有什么意见吗?
错误信息 -
======================================================================
FAIL: test_get_all_courses (tests.test_courses.TestApiCourses)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/rem/git/udemy/tests/test_courses.py", line 136, in test_get_all_courses
courses = self.app.courses.get_all(page=1, page_size=2)
File "/Users/rem/.virtualenvs/udemyapp/lib/python2.7/site-packages/responses.py", line 536, …Run Code Online (Sandbox Code Playgroud) 我正在尝试比较两个不同字符串的第一个字符(依此类推),以根据这些结果形成一个新字符串.这是我尝试过的,但它将每个列表的每个元素相互比较.
def compare(a,b):
s = ""
for x in a:
for y in b:
if x == y:
s+=str(x)
else:
s+=str(y)
Run Code Online (Sandbox Code Playgroud)
这似乎是一个简单的问题,但我被卡住了.