No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python async await Simple Example

by Khaleel O.
January 2, 2022
in Python
Reading Time: 3 mins read
A A
python async await simple example
python async await simple example

Hi! Let’s do a simple example of async/await in Python. We will be using Python 3.8.10. Let’s go! ⚡⚡✨✨

The async/await syntax is what is used by the asyncio library to perform multitasking in Python. Recall that multitasking in programming is all about getting better performance by having multiple processes work at the same time. The processes may execute in-sequence, out-of-sequence, they will overlap each other and run in parallel but the final outcome will be unaffected.

The asyncio library offers a simple and safe way to achieve multitasking, but there are other ways to accomplish the same thing in Python. Now, let’s write some code:

import asyncio, time, datetime

async def main():
    print(f'{datetime.datetime.strptime(time.ctime(), "%c")} Start')
    await asyncio.sleep(2.0)
    print(f'{datetime.datetime.strptime(time.ctime(), "%c")} Stop')

asyncio.run(main())

Let’s explain what is happening here:

  1. First, import the asyncio library. If you don’t have it installed by default you can use the simple command pip install asyncio to install it. We also import the time and datetime libraries.
  2. The function main() is defined with the syntax keywords async def. This is our coroutine function, and the statement block is our coroutine function definition. This function will return a coroutine object. A coroutine is a function that can be entered, exited or resumed at many different points.
  3. We print the current date and time, including the seconds so we can see how the coroutine works.
  4. The await keyword expression allows us to use awaitable objects. Awaitable objects include coroutines, tasks and futures. The method asyncio.sleep() is a coroutine and also an awaitable object. The sleep() method will block or stop the execution of the program for the specified number of seconds. The number of seconds is supplied as the delay parameter. In this case the delay is only 2 seconds.
  5. The await keyword can only be used inside the coroutine function. As of Python 3.7 both async and await became keywords/reserved words in python.
  6. After the program sleeps for 2 seconds, it will execute the second print statement and print the stop time.
  7. The asyncio.run() method is what will execute our coroutine and return the result. The coroutine name in this case is the name of our coroutine function, main(). This method will create a new event loop and close it at the end.

That’s it! Once all goes well, when we execute this code we will get the first statement followed by a pause of 2 seconds then a second statement will be printed to the screen. See below output and note the difference of seconds between the two dates:

#output
#2022-01-02 21:07:52 Start
#2022-01-02 21:07:54 Stop

See the difference in the time? Exactly 2 seconds! Thanks for reading our simple example of async/await. You can find a more complex example HERE and find the asyncio documentation HERE. Good luck! 👌👌👌

Tags: asyncasyncioawait
Previous Post

Python argparse Comma Separated List

Next Post

Python async await Example

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy