在Python中使用asyncio时如何避免运行时错误?

时间:2018-08-17 11:48:44

标签: python python-3.x python-asyncio

我正在使用Python的异步功能。学习了使用方法之后。

我更新了代码以进行数据分析。它在python3.5中工作正常。 但是,当我从Python3.5更新到Python3.6时,出现运行时错误。

我的用法很简单。

首先,在名为“ runner.py”的文件中创建异步用法,如下所示:

#include<stdio.h>
#include<stdlib.h>
int countDigits(int num) {
    int count = 0;
    while(num) {
        num = num/10;
        count++;
    }
    return count;
}
char* buildCharArray(int num, int number_of_digits) {
    /*
    Dynamic memory allocation for character array. Otherwise, if we create char number[number_of_digits] and return it,
    it will be created with automatic storage class and references to it will become invalid once it leaves its declaring scope.
    */
    char *number = malloc(number_of_digits);
    int i=0;
    while(num) {
         number[i]= num%10;
         num = num/10;
         i++;
    }
    return number;
}
void buildNewNum(char *number, int number_of_digits) {
    int new_number = 0;
    int i=0, j=number_of_digits-1;
    while(i<=j) {
        if(i == j) {
            new_number = new_number*10 + *(number+j);
            break;
        }
        new_number = new_number*10 + *(number+j);
        new_number = new_number*10 + *(number+i);
        i++;
        j--;
    }
    printf("\n Modified number is: %d", new_number);
    free(number);
}
void firstlastAlternate(int num) {
    int number_of_digits = countDigits(num);
    char *number = buildCharArray(num, number_of_digits);
    buildNewNum(number, number_of_digits);
}

int main(void) {
    int num;
    printf("\n Enter any number: ");
    scanf("%d", &num);
    firstlastAlternate(num);
    return 0;
}

然后,从另一个名为“ main.py”的文件导入

import asyncio as aio
def async_usage():
    loop = aio.get_event_loop()
    task = loop.create_task(some_task())
    loop.run_until_comeplete(task)

当我运行main.py时,发生运行时错误。

  

该错误表明此事件循环已在运行。

顺便说一下,这些代码和运行已在jupyter笔记本中完成

如何避免这种情况?

在运行它之前,我曾尝试添加类似import async_usage from runner async_usage() 的代码,但是它无法正常工作。

我知道只有一个循环可以同时退出,但是我没有在Runner.py中运行循环。

我该如何解决?

thx。

2 个答案:

答案 0 :(得分:0)

我认为您正在Windows平台上运行。

loop = asyncio.get_event_loop()将创建一个_WindowsSelectorEventLoop对象。

运行默认值为True。因此您应该删除“ loop.run_until_complete(some_task())”

<_ WindowsSelectorEventLoop运行=正确关闭= False调试= False>

如果在linux平台上运行,您将获得_UnixSelectorEventLoop对象。

<_ UnixSelectorEventLoop running =假关闭=假调试=假>

没关系。

答案 1 :(得分:0)

感谢以上提供您答案的同志。我知道了。 与我的代码无关,而与笔记本有关。 如果您使用的是笔记本,请运行下面的代码,您将发现当前循环正在运行。

import asyncio as aio
default_loop = aio.get_event_loop()
if default_loop.is_running():
    print("The current loop is running!")

为进一步验证,如果您随后运行以下代码,则笔记本计算机将关闭

default_loop.stop()

然后笔记本外壳将自动重新启动,并且当前笔记本中的内存已消失。

如果您在python shell中执行此操作,则不会发生任何事情。

因此,要做的是不使用run_until_complete,任务将自动在当前循环中运行。