Python:如何使脚本在返回有效的字符串变量后继续

2024-09-30 10:39:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于python定义流的问题:

def testCommandA () :
  waitForResult = testCommandB ()
  if result != '' :
     print 'yay'

有没有办法让waitForResult等待testCommandB返回一些东西(不仅仅是一个空字符串)?有时testCommandB将不产生任何东西(空字符串),我不想传递空字符串,但只要我在waitForResult中得到一个字符串,testCommandA就会继续运行。有可能吗?你知道吗

提前谢谢


Tags: 字符串if定义defresultprintyay办法
2条回答

只需从testCommandB返回它不是空字符串的地方。也就是说,拥有testCommandB块直到它有一个有意义的值。你知道吗

# Start with an empty string so we run this next section at least once
result = ''
# Repeat this section until we get a non-empty string
while result == '':
    result = testCommandB()
print("result is: " + result)

注意,如果testCommandB()没有阻塞,这将导致100%的CPU利用率,直到它完成。另一个选项是检查之间的sleep。此版本每十分之一秒检查一次:

import time

result = ''
while result == '':
    time.sleep(0.1)
    result = testCommandB()
print("result is: " + result)

相关问题 更多 >

    热门问题