Python3 delete file – Python: How to remove files by matching pattern | wildcards | certain extensions only?

Python- How to remove files by matching pattern, wildcards, certain extensions only

Python find files matching pattern: In this ultimate tutorial, we are going to discuss how to remove files from a directory based on a matching pattern or wildcard, or specific extensions. You will get the information regarding these also, Python Os.Remove Wildcard, Python Delete File Wildcard, Python Remove Files With Wildcard, Python Delete Files With Wildcard, Python Remove Files Wildcard, Python Remove Files Matching Pattern, Delete File Python, Remove File Python, Python Os Delete File, Delete A File Python, Python Remove File Wildcard, Python Delete Files Matching Pattern, Python Remove Directory.

How to delete text files using different techniques?

Python remove all files in directory: Let’s discuss how to delete text files using different techniques, Suppose we have a directory that contains some log files and some text files and we want to delete all .txt files from that directory.

Then, continue your read so that you can successfully learn to remove files by matching patterns or wildcards by the following methods and techniques.

Remove files by pattern using glob.glob() & os.remove()

Python3 delete file: First, we will get a list of all file paths that match the specified patterns using glob.glob() and then delete all text files.

import os
import glob
# Get a list of all the file paths that ends with .txt from in specified directory
fileList = glob.glob('C://Users/HP/Desktop/A plus topper/*.txt')
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)

So you can see that it will remove all ‘.txt’ files in the directory ‘C:\\Users\HP\Desktop\A plus topper\*.txt’. It will remove all text files because we mention” *.txt “.

Get the list of files using glob.glob()

Python os remove file: glob.glob() accepts path name and finds the path of all the files that match the specified pattern. By default recursive parameter is False, which means that it will find files in the main directory, not in a subdirectory.

glob.glob(pathname, *, recursive=False)

As we have seen by this approach we can not recursively delete files from subdirectories. For that, we will find another solution,

Read More:

Recursively Remove files by matching pattern or wildcard

Python delete all files in directory: It will search all the ‘txt’ files including files in subdirectories because we will use 'C://Users/HP/Desktop/A plus topper/**/*.txt'‘ **  ‘ in it.

Then we can iterate over the list and delete each file one by one using os.remove().

import os
import glob
# get a recursive list of file paths that matches pattern including sub directories
fileList = glob.glob('C://Users/HP/Desktop/A plus topper/**/*.txt', recursive=True)
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except OSError:
        print("Error while deleting file")

It will delete all the text files from the directory and its sub-directories.

Recursively Remove files by matching pattern or wildcard using os.walk()

Python rm file: In this, we are going to use os.walk(). It generates filename in the given directory by walking over the tree structure in a top-down or bottom-up approach.

os.walk(top, topdown=True, onerror=None, followlinks=False)

It will return a tuple consisting of the main directory, a list of all subdirectories, and a list of all file names in the main directory.

Let’s use this os.walk() to get a list of all files in a given directory that matches a pattern. Then delete those files,

import os
import fnmatch
# Get a list of all files in directory
for rootDir, subdirs, filenames in os.walk('C://HP/Users/Desktop/A plus topper'):
    # Find the files that matches the given patterm
    for filename in fnmatch.filter(filenames, '*.txt'):
        try:
            os.remove(os.path.join(rootDir, filename))
        except OSError:
            print("Error while deleting file")

It will delete all the text files from the directory and also from its subdirectories.

Now we are going to create a Generic function to delete all the files from a given directory based on a matching pattern and it will also return the names of the files that were not deleted due to some error.

import os
import fnmatch
'''
Generic function to delete all the files from a given directory based on matching pattern
'''
def removeFilesByMatchingPattern(dirPath, pattern):
    listOfFilesWithError = []
    for parentDir, dirnames, filenames in os.walk(dirPath):
        for filename in fnmatch.filter(filenames, pattern):
            try:
                os.remove(os.path.join(parentDir, filename))
            except:
                print("Error while deleting file : ", os.path.join(parentDir, filename))
                listOfFilesWithError.append(os.path.join(parentDir, filename))
    return listOfFilesWithError
listOfErrors = removeFilesByMatchingPattern('/home/varung/Documents/python/logs/', '*.txt')
print('Files that can not be deleted : ')
for filePath in listOfErrors:
    print(filePath)

So in the above code, you can see that it will also return file names that can not be deleted.

Read also: How to delete a directory recursively using shutil.rmtree()

Analyze these: 

  • How To Delete File In Python
  • Python Remove File Wildcard
  • Delete Files Python
  • Python Rm File

Conclusion:

In this article, we have seen how to remove files from a directory based on matching patterns or wildcards, or certain extensions.

print entire dataframe panda – Python Pandas: How to display full Dataframe i.e. print all rows & columns without truncation

Python Pandas- How to display full Dataframe i.e. print all rows & columns without truncation

Print entire dataframe pandas: In this tutorial, we will discuss the different methods to display or print full Data frame i.e. print all rows & columns without truncation. So, get into this page and learn completely about Pandas display full data frame in python i.e. how to print all rows & columns without truncation. Also, you can get a clear idea of how to display full data frame from here. Pandas will be displayed column in the full data frame. And also include pandas print without truncation, python print data frame without truncation, pandas print data frame without truncation, display full data frame pandas, pandas print column without truncating, pandas dataframe print without truncation etc…

Display Full Contents of a Dataframe

Pandas show all rows: Pandas implement an operating system to customize the behavior & display similar stuff. By applying this benefits module we can configure the display to show the complete dataframe rather than a truncated one. A function set_option()is provided in pandas to set this kind of option,

pandas.set_option(pat, value)

It sets the value of the defined option. Let’s use this to display the full contents of a dataframe.

Setting to display All rows of Dataframe

Print all columns pandas: In pandas when we print a dataframe, it displays at max_rows number of rows. If we have more rows, then it truncates the rows.

pandas.options.display.max_rows

This option outlines the maximum number of rows that pandas will present while printing a dataframe. The default value of max_rows is 10.

In case, it is set to ‘None‘ then it implies unlimited i.e. pandas will display all the rows in the dataframe. Let’s set it to None while printing the contents of above-created dataframe empDfObj,

# Default value of display.max_rows is 10 i.e. at max 10 rows will be printed.
# Set it None to display all rows in the dataframe
pd.set_option('display.max_rows', None)

Let’s examine the contents of the dataframe again,

print(empDfObj)

Output: 

    A B ... Z AA
0 jack 34 ... 122 111
1 Riti 31 ... 222 211
2 Aadi 16 ... 322 311
3 Sunil 41 ... 422 411
4 Veena 33 ... 522 511
5 Shaunak 35 ... 622 611
6 Shaun 35 ... 722 711
7 jack 34 ... 122 111
8 Riti 31 ... 222 211
9 Aadi 16 ... 322 311
10 Sunil 41 ... 422 411
11 Veena 33 ... 522 511
12 Shaunak 35 ... 622 611
13 Shaun 35 ... 722 711
14 jack 34 ... 122 111
15 Riti 31 ... 222 211
16 Aadi 16 ... 322 311
17 Sunil 41 ... 422 411
18 Veena 33 ... 522 511
19 Shaunak 35 ... 622 611
20 Shaun 35 ... 722 711
21 jack 34 ... 122 111
22 Riti 31 ... 222 211
23 Aadi 16 ... 322 311
24 Sunil 41 ... 422 411
25 Veena 33 ... 522 511
26 Shaunak 35 ... 622 611
27 Shaun 35 ... 722 711
28 jack 34 ... 122 111
29 Riti 31 ... 222 211
30 Aadi 16 ... 322 311
31 Sunil 41 ... 422 411
32 Veena 33 ... 522 511
33 Shaunak 35 ... 622 611
34 Shaun 35 ... 722 711
35 jack 34 ... 122 111
36 Riti 31 ... 222 211
37 Aadi 16 ... 322 311
38 Sunil 41 ... 422 411
39 Veena 33 ... 522 511
40 Shaunak 35 ... 622 611
41 Shaun 35 ... 722 711
42 jack 34 ... 122 111
43 Riti 31 ... 222 211
44 Aadi 16 ... 322 311
45 Sunil 41 ... 422 411
46 Veena 33 ... 522 511
47 Shaunak 35 ... 622 611
48 Shaun 35 ... 722 711
49 jack 34 ... 122 111
50 Riti 31 ... 222 211
51 Aadi 16 ... 322 311
52 Sunil 41 ... 422 411
53 Veena 33 ... 522 511
54 Shaunak 35 ... 622 611
55 Shaun 35 ... 722 711
56 jack 34 ... 122 111
57 Riti 31 ... 222 211
58 Aadi 16 ... 322 311
59 Sunil 41 ... 422 411
60 Veena 33 ... 522 511
61 Shaunak 35 ... 622 611
62 Shaun 35 ... 722 711

[63 rows x 27 columns]

Also Check:

How to print an entire Pandas DataFrame in Python?

Pandas print dataframe: When we use a print large number of a dataset then it truncates. In this article, we are going to see how to print the entire pandas Dataframe or Series without Truncation or print pandas dataframe without truncation or print df without truncating.

The complete data frame is not printed when the length exceeds.

import numpy as np
from sklearn.datasets import load_iris
import pandas as pd
  
# Loading irirs dataset
data = load_iris()
df = pd.DataFrame(data.data,columns = data.feature_names)
print(df)

Output:

How-to-print-an-entire-Pandas-DataFrame-in-Python.png

By default our complete contents of out dataframe are not printed, output got truncated. It printed only 10 rows all the remaining data is truncated. Now, what if we want to print the full dataframe without any truncation.

Four Methods to Print the entire pandas Dataframe

  1. Use to_string() Method
  2. Use pd.option_context() Method
  3. Use pd.set_options() Method
  4. Use pd.to_markdown() Method

1. Using to_string()

Pandas print all columns: This is a very simple method. That is why it is not used for large files because it converts the entire data frame into a string object. But this works very well for data frames for size in the order of thousands.

import numpy as np
from sklearn.datasets import load_iris
import pandas as pd
  
data = load_iris()
df = pd.DataFrame(data.data,
                  columns = data.feature_names)
  
# Convert the whole dataframe as a string and display
print(df.to_string())

Output:

How-to-display-full-Dataframe-i.e.-print-all-rows-columns-without-truncation_output.pn

So in the above example, you have seen it printed all columns without any truncation.

2. Using pd.option_context()

Pandas print row: option_context() and set_option() both methods are identical but there is only one difference that is one changes the settings and the other do it only within the context manager scope.

import numpy as np
from sklearn.datasets import load_iris
import pandas as pd
  
data = load_iris()
df = pd.DataFrame(data.data, 
                  columns = data.feature_names)
  
with pd.option_context('display.max_rows', None,'display.max_columns', None,
    'display.precision', 3,
                       ):
print(df)

Output:

How-to-display-full-Dataframe-i.e.-print-all-rows-columns-without-truncation_output.pn

In the above example, we are used ‘display.max_rows‘ but by default its value is 10 & if the dataframe has more rows it will truncate. So it will not be truncated we used None so all the rows are displayed.

3. Using pd.set_option()

Python show all columns: This method is similar to pd.option_context() method and takes the same parameters. pd.reset_option(‘all’) used to reset all the changes.

import numpy as np
from sklearn.datasets import load_iris
import pandas as pd
  
data = load_iris()
df = pd.DataFrame(data.data,
                  columns = data.feature_names)
  
# Permanently changes the pandas settings
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)
  
# All dataframes hereafter reflect these changes.
print(df)
  
print('**RESET_OPTIONS**')
  
# Resets the options
pd.reset_option('all')
print(df)

Output:

How-to-display-full-Dataframe-i.e.-print-all-rows-columns-without-truncation_output.pn

**RESET_OPTIONS**

: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.

How-to-print-an-entire-Pandas-DataFrame-in-Python.png

4. Using to_markdown()

Print dataframe: This method is similar to the to_string() method as it also converts the data frame to a string object and also adds styling & formatting to it.

import numpy as np
from sklearn.datasets import load_iris
import pandas as pd
  
data = load_iris()
df = pd.DataFrame(data.data,
                  columns=data.feature_names)
  
# Converts the dataframe into str object with fromatting
print(df.to_markdown())

Output:
How-to-display-full-Dataframe-i.e.-print-all-rows-columns-without-truncation_output.pn

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Answer these:

  1. How to print entire dataframe in python
  2. How to print pandas dataframe without truncation
  3. How to display full dataframe in pandas
  4. How to view full dataframe in python
  5. How to see the whole dataframe in python

Also Refer: How to get & check data types of Dataframe columns in Python Pandas

Read more Articles on Python Data Analysis Using Pandas

How to get first key in Dictionary – Python | Get the First Key in Python Dictionary

How to get first key in Dictionary – Python

How to get First Key in a Dictionary Python: In this tutorial, we will discuss different ways to get the first key in a dictionary. Later, we will see & learn how to choose the first N Keys of a dictionary in Python.

Get the first key from a dictionary using keys() method

Python print first item in dictionary: Dictionary stores elements in key-value pairs.Dictionary act as a container in python. Dictionary provided keys() function which we will use to fetch all keys in it and after that we select the first key from a sequence.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first key in a dictionary
first_key = list(word_freq.keys())[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Get first element of dictionary python: In the above example, you can see that first we have fetched all dictionary elements and by using indexing we find out the first key value.

Do Refer:

Here is another way to do the same,

Another Way for How to get First Key in Dictionary Python

Print keys of dictionary python: By using this method, it will convert all keys of the dictionary to a list and then we can select the first element from the list.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first ket in a dictionary
first_key = list(word_freq)[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

In the above example, we didn’t call the keys() function. We created a list of keys from the dictionary and selected the first item from it.

Get first key in a dictionary using iter() & next()

What we have done above that was not a perfect solution because first, we created a list and then fetch the first key in a dictionary. It is very difficult to apply that method in a large number of dictionaries. First, we iterate the object of keys using the iter() function then we apply the next() function on it for getting the first element.

Get first key in a dictionary using iter() & next()

This is an efficient solution because didn’t iterate over all the keys in a dictionary, we just selected the first one.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first key in a dictionary
first_key = next(iter(word_freq))
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Get the First Key in Dictionary Using list() Function

Also, there is a possible way to convert the dict type into a list using thelist() function at first and later get the first key at the 0th index of the dictionary.

my_dict = { 'Russia': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

print(list(my_dict.keys())[0])

Result:

Russia

Get the First Key in Dictionary Using for Loop

One more easiest way to get the initial key in a dictionary is using theforloop. After getting the first key of the dictionary break the loop.

Let’s see an example on it:

my_dict = { 'London': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

for key, value in my_dict.items():
  print(key)
  break

Output:

London

Get first N keys from a Dictionary in Python

To select the first N keys from a dictionary, convert the keys of a dictionary to a list and then select the first N entries from that. For example, let’s see how to select the first 3 keys from a dictionary,

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first ket in a dictionary
first_key = list(word_freq)[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Conclusion on Get First value in a dictionary of string and int

In this article, we have seen discuss different ways to find out the first key of a dictionary in python. All these dictionary keys methods in python help to find easily the key value in a dictionary of string and int word_freq. Get first key of the dictionary in python information completely from this article.

Compiling C++ with Debug Symbols – gdb debugger Tutorial & Examples

g++ gdb: In this article we are going to discuss how to debugging using gdb debugger in C++.

gdb debugger is an application for execute C or C++ program to check the code working and it’s crashes.There are so many task which can be done using gdb debugger,like check prgram,run code,test new conditions and find out errors.

Compile Code with Debug Symbols

We should debug C or C++ program in debug mode.We should use -g option in it.

Below is our first step to debug program using gdb,

g++ -g filename.cpp -o Sample

Now there is two way to debug using gdb debugger;

1.Debugging with executable name,

gdb filename

It will read symbols from ‘filename’ after this type below command;

(gdb) run

2.Start gdb alone without debugging-

gdb

Now give the file name for execution,

(gdb) file filename

After that your application start debugging in debug mode.

Passing Command Line Arguments while debugging

We can also pass command argument at the time of debugging.For this we use below command;

Reading symbols from filename...done.
(gdb) run 1 2 3

There are so many different command in gdb debugger to know them you can run help command,

(gdb) help

It will show you all command list and their working,like below;

Command Description
help Provides information about a topic or commands you can use
file Indicates which file to debug
run Executes the program under GDB
break Adds breakpoints to stop the program execution temporary
delete Deletes breakpoints
clear Deletes breakpoints for a specific function
continue Resets the program after a breakpoint triggers
step Runs the current source line and stops before executing the next one
ext Runs the current source line. However, if the line is a function call, the debugger will fully execute the function before the execution stops again
until Runs the current source line. If you are at the beginning of a loop, the debugger runs until the loop ends
list Prints a certain list from the source code
print Prints values of certain expressions

How do I exit the debugging

For exiting you have to write quit command and you will be out from debug mode,

(gdb) quit

And if you again want to come in debug mode then you will just press “Ctrl-C”.

Conclusion:

In this article we have discussed how to debugging using gdb debugger in C++.Thank you!

How to execute python program – How to Run a Python Script

How to execute python program: Python is not just one of the leading programming languages, but also a top choice for dealing with big data and data science projects. The fact that it is among the easiest languages to learn makes the high-level, interpreted, general-purpose programming language even more lucrative.

For using Python on a system, the user first needs to install the Python environment. It will also install the Python interpreter, which is responsible for carrying out Python code execution. It is possible to run Python code directly from the terminal using the Python interpreter.

Python is a well known high-level programming language. The Python script is basically a file containing code written in Python. The file containing python script has the extension ‘.py’ or can also have the extension ‘.pyw’ if it is being run on a windows machine. To run a python script, we need a python interpreter that needs to be downloaded and installed.

Scripts vs Modules:

A Python script is a collection of commands in a file designed to be executed like a program. The file can of course contain functions and import various modules, but the idea is that it will be run or executed from the command line or from within a Python interactive shell to perform a specific task. Often a script first contains a set of function definitions and then has the main program that might call the functions.

Scripts are always processed by some kind of interpreter, which is responsible for executing each command sequentially.

A plain text file containing Python code that is intended to be directly executed by the user is usually called script, which is an informal term that means top-level program file.

On the other hand, a plain text file, which contains Python code that is designed to be imported and used from another Python file, is called module.

So, the main difference between a module and a script is that modules are meant to be imported, while scripts are made to be directly executed.

Different ways to run Python Script:

  1. Interactive Mode
  2. Command Line
  3. Text Editor
  4. IDE (PyCharm)

 

1.Interactive Mode:

Interactive mode, also known as the REPL provides us with a quick way of running blocks or a single line of Python code. The code executes via the Python shell, which comes with Python installation. Interactive mode is handy when you just want to execute basic Python commands or you are new to Python programming and just want to get your hands dirty with this beautiful language.

To access the Python shell, open the terminal of your operating system and then type “python”. Press the enter key and the Python shell will appear. This is the same Python executable you use to execute scripts, which comes installed by default on Mac and Unix-based operating systems.

How to Run a Python Script_interactive mode
The >>> indicates that the Python shell is ready to execute and send your commands to the Python interpreter. The result is immediately displayed on the Python shell as soon as the Python interpreter interprets the command.

To run your Python statements, just type them and hit the enter key. You will get the results immediately, unlike in script mode. For example, to print the text “Hello World”, we can type the following:

Interactive Mode output

2.Command Line:

To run a Python script store in a ‘.py’ file in command line, we have to write ‘python’ keyword before the file name in the command prompt.

python hello.py

You can write your own file name in place of ‘hello.py’.

Using command line
3.Text Editor :

Python’s standard distribution includes IDLE as the default IDE, and you can use it to write, debug, modify, and run your modules and scripts.

Other IDEs such as Eclipse-PyDev, PyCharm, Eric, and NetBeans also allow you to run Python scripts from inside the environment.

Advanced text editors like Sublime Text andVisual Studio Code also allow you to run your scripts.

4.IDE (PyCharm):

To run Python script on a IDE like PyCharm you will have to do the following:

  • Create a new project.
  • Give a name to that project as ‘NewProject’ and click on Create.
  • Select the root directory with the project name we specified in the last step. Right click on it, go in New and click on ‘Python file’ option. Then give the name of the file as ‘hello’ (you can specify any name as per your project requirement). This will create a ‘hello.py’ file in the project root directory.
    Note: You don’t have to specify the extension as it will take it automatically.

Using IDE (PyCharm)
Now write the below Python script to print the message:

print('Hello World !')

Using IDE (PyCharm) output

Conclusion:

With the reading of this tutorial, you have acquired the knowledge and skills you need to be able to run Python scripts and code in several ways and in a variety of situations and development environments.

Python timestamp to string – Python: How to convert a timestamp string to a datetime object using datetime.strptime()

Python- How to convert a timestamp string to a datetime object using datetime.strptime()

Python timestamp to string: In this tutorial, we will learn how to convert a timestamp string to a datetime object using datetime.strptime(). Also, you can understand how to to create a datetime object from a string in Python with examples below.

String to a DateTime object using datetime.strptime()

Python convert timestamp to string: Thestrptime()method generates a datetime object from the given string.

Datetime module provides a datetime class that has a method to convert string to a datetime object.

Syntax:

datetime.strptime(date_string, format)

So in the above syntax, you can see that it accepts a string containing a timestamp. It parses the string according to format codes and returns a datetime object created from it.

First import datetime class from datetime module to use this,

from datetime import datetime

Also Read:

Complete Format Code List

Format Codes Description Example
%d Day of the month as a zero-padded decimal number 01, 02, 03, 04 …, 31
%a Weekday as the abbreviated name Sun, Mon, …, Sat
%A Weekday as full name Sunday, Monday, …, Saturday
%m Month as a zero-padded decimal number 01, 02, 03, 04 …, 12
%b Month as an abbreviated name Jan, Feb, …, Dec
%B Month as full name January, February, …, December
%y A Year without century as a zero-padded decimal number 00, 01, …, 99
%Y A Year with a century as a decimal number 0001, …, 2018, …, 9999
%H Hour (24-hour clock) as a zero-padded decimal number 01, 02, 03, 04 …, 23
%M Minute as a zero-padded decimal number 01, 02, 03, 04 …, 59
%S Second as a zero-padded decimal number 01, 02, 03, 04 …, 59
%f Microsecond as a decimal number, zero-padded on the left 000000, 000001, …, 999999
%I Hour (12-hour clock) as a zero-padded decimal number 01, 02, 03, 04 …, 12
%p Locale’s equivalent of either AM or PM AM, PM
%j Day of the year as a zero-padded decimal number 01, 02, 03, 04 …, 366

How strptime() works?

In thestrptime()class method, it takes two arguments:

  • string (that be converted to datetime)
  • format code

In the accordance with the string and format code used, the method returns its equivalent datetime object.

Let’s see the following example, to understand how it works:

python strptime method example

where,

%d – Represents the day of the month. Example: 01, 02, …, 31
%B – Month’s name in full. Example: January, February etc.
%Y – Year in four digits. Example: 2018, 2019 etc.

Examples of converting a Time String in the format codes using strptime() method

Timestamp to string python: Just have a look at the few examples on how to convert timestamp string to a datetime object using datetime.strptime() in Python and gain enough knowledge on it.

Example 1:

Let’s take an example,

from datetime import datetime
datetimeObj = datetime.strptime('2021-05-17T15::11::45.456777', '%Y-%m-%dT%H::%M::%S.%f')
print(datetimeObj)
print(type(datetimeObj))

Output:

2021-05-17 15:11:45.456777
<class 'datetime.datetime'>

So in the above example, you can see that we have converted a time string in the format “YYYY-MM-DDTHH::MM::SS.MICROS” to a DateTime object.

Let’s take another example,

Example 2:

from datetime import datetime
datetimeObj = datetime.strptime('17/May/2021 14:12:22', '%d/%b/%Y %H:%M:%S')
print(datetimeObj)
print(type(datetimeObj))

Output:

2021-05-17 14:12:22
<class 'datetime.datetime'>

So this is the other way to show timestamp here we have converted a time string in the format “DD/MM/YYYY HH::MM::SS” to a datetime object.

Example 3:

If we want to show the only date in this format “DD MMM YYYY”. We do like this,

from datetime import datetime
datetimeObj = datetime.strptime('17 May 2021', '%d %b %Y')
# Get the date object from datetime object
dateObj = datetimeObj.date()
print(dateObj)
print(type(dateObj))

Output:

2021-05-17
<class 'datetime.date'>

Example 4:

So if we want to show only time “‘HH:MM:SS AP‘” in this format. We will do like that,

from datetime import datetime
datetimeObj = datetime.strptime('08:12:22 PM', '%I:%M:%S %p') 
# Get the time object from datetime object 
timeObj = datetimeObj.time()
print(timeObj) 
print(type(timeObj))

Output:

20:12:22
<class 'datetime.time'>

Example 5:

If we want to show our timestamp in text format. We will execute like that,

from datetime import datetime
textStr = "On January the 17th of 2021 meet me at 8 PM"
datetimeObj = datetime.strptime(textStr, "On %B the %dth of %Y meet me at %I %p")
print(datetimeObj)

Output:

2021-01-17 20:00:00

Conclusion:

So in the above tutorial, you can see that we have shown different methods of how to convert a timestamp string to a datetime object using datetime.strptime(). Thank you!

Pad string with spaces python – Python: How to pad strings with zero, space or some other character?

Python-How to pad strings with zero, space or some other character

Pad string with spaces python: In this tutorial, we are going to discuss how to do padding of strings using zero, space, or some other character. Also, you can get complete knowledge of the methods used for padding strings in Python. So, let’s get started on learning How to pad strings with Zero, Space, or some other character.

Types of Padding in Python

There are two types of padding:

  1. Left padding
  2. Right padding

1. Left padding of string in Python

Python pad string with spaces: Left padding means adding a given character on the left side of a string.

For Example – If we pad three zeros in string 6 i.e, ‘0006’, or if we pad three space in string i.e,’6′

numStr = "6"
print('Original String :', numStr)
# Left pad the string with 0 to make it's length 4
numStr = numStr.zfill(4)
print('Updated String :' , numStr)

Output:

Original String : 6
Updated String : 0006

So in the above example, we have used'string.zfill(s, width)'to pad a given string on the left with zeros (0).

Also Check:

Left pad a string with space using string.rjust()

Python zero pad: In this, we are going to use string.rjust() to add space in a given string.

numStr = "6"
print('Original String :', numStr)
# Make string right justified of length 4 by padding 3 spaces to left
numStr = numStr.rjust(4, ' ')
print('Updated String :', numStr)

Output:

Original String : 6
Updated String :    6

Left pad a string with some character using string.rjust()

Python pad string: For adding any character to our string we will use string.rjust() and pass that character in it.

numStr = "6"
print('Original String :', numStr)
# Make string right justified of length 4 by padding 3 '-' to left
numStr = numStr.rjust(4, '-')
print('Updated String :', numStr)

Output:

Original String : 6
Updated String : ---6

2. Right padding of string in Python

Python pad string: Right padding means adding a given character on the right side of the string.

Example- If we have a number string i.e. “ram”. Now we want to convert this string of length 3 to a string of length 6 by,

  • Right padding three zeros to the string i.e. “ram000”
  • Right padding three-space to the string i.e. “ram “
  • Right padding three characters to the string i.e. “ram—“

Right pad a string with zeros using string.ljust()

string.ljust() is used for padding a given character to the right of string to make its a length equal to the given width.

numStr = "67"
print('Original String :', numStr)
# Make string left justified of length 5 by padding 3 0s to the right of it
numStr = numStr.ljust(5, '0')
print('Updated String :', numStr)

Output:

Original String : 67
Updated String : 67000

Right pad a string with space using string.ljust()

In this, we will use string.ljust() to pad given character,

userName = "Shikha"
print('Original String :', userName)
# Make string left justified of length 7 by padding 3 spaces to the right of it
userName = userName.ljust(7, ' ')
print('Updated String :' , userName, 'is')

Here 3 spaces are padded to the right of the given string to make its length 9.

Output:

Original String : Shikha
Updated String : Shikha   is

Right pad a string with some character using string.ljust()

We can pass a character in string.ljust(s, width[, fillchar]) to right pad the given string by that passed character.

userName = "shikha"
print('Original String :', userName)
# Make string left justified of length 7 by padding 3 '-' to the right of it
userName = userName.ljust(7, '-')
print('Updated String :' , userName)

Output:

Here, three ‘-‘ are padded to the right of the given string to make its length 9.

Original String : shikha
Updated String : shikha---

Conclusion:

In this article, you have seen that how to do padding of strings using zero, space, or some other character.

Thank you!

CPP 11 Multithreading – Part 2: Joining and Detaching Threads | std::thread::join() & std::thread::detach() Methods with Examples

CPP 11 Multithreading – Part 2- Joining and Detaching Threads

Thread join c++: In the previous article, we have discussed about How to trim strings in C++ using Boost String Algorithm Library. Let us learn how to find Multithreading – Part 2 in C++ Program.

Let’s discover this tutorial for getting more knowledge about C++11 Multithreading Part-2.  Here we are going to learn what is joining and detaching threads of std::thread. Apart from that, you may also see the explanation of std::thread::join() & std::thread::detach() Methods with Examples. So, stay tuned to this tutorial easily via available quick links.

Joining Threads with std::thread::join()

Std thread join: When the first thread is started then the other thread that is going to start yet should wait for the first thread to finish. For this, another we need to call the join() function on the std::thread object.

Syntax:

std::thread th(funcPtr);

// Some Code

th.join();

Suppose Main Thread has to start 10 Worker Threads and after starting all these threads, the main function will wait for them to finish. After joining all the threads the main function will continue.

So, let’s take an example. There is one main thread and some worker threads after joining all the threads the main function will continue. The main function will wait for them to finish.

#include <iostream>
#include <thread>
#include <algorithm>
#include <vector>
#include <functional>
class WorkerThread
{
public:
    void operator()()     
    {
        std::cout<<"Worker Thread "<<std::this_thread::get_id()<<" is Executing"<<std::endl;
    }
};
int main()  
{
    std::vector<std::thread> threadList;
    for(int i = 0; i < 10; i++)
    {
        threadList.push_back( std::thread( WorkerThread() ) );
    }
    // Now wait for all the worker thread to finish i.e.
    // Call join() function on each of the std::thread object
    std::cout<<"wait for all the worker thread to finish"<<std::endl;
    std::for_each(threadList.begin(),threadList.end(), std::mem_fn(&std::thread::join));
    std::cout<<"Exiting from Main Thread"<<std::endl;
    return 0;
}

Detaching Threads using std::thread::detach()

Detached threads are background threads sometimes also called daemon threads. To detach a thread we need to call std::detach() function on std::thread object. ie.,

std::thread th(funcPtr);
th.detach();

Once you call the detach(), then the std::thread object is no longer connected with the actual thread of execution.

Also Check:

Be cautious with calling detach() and join() on Thread Handles

We have to be careful on calling detach() and join() on thread handles. We are going to discuss some cases below for this:

Case 1: Never call join() or detach() on std::thread object with no associated executing thread

std::thread threadObj( (WorkerThread()) );
   threadObj.join();
   threadObj.join(); // It will cause Program to Terminate

When a join() function called on a thread object, join returns 0 then that ‘td::thread’ object has no associated thread with it. If the join() function again called on such an object then it will cause the program to Terminate. Similarly, detach() function will work.

Syntax:

std::thread threadObj( (WorkerThread()) );
   threadObj.detach();
   threadObj.detach(); // It will cause Program to Terminate

Before calling join() or detach() we should check if the thread is join-able every time or not,

std::thread threadObj( (WorkerThread()) );
   if(threadObj.joinable())
   {
       std::cout<<"Detaching Thread "<<std::endl;
       threadObj.detach();
   }
   if(threadObj.joinable())    
   {
       std::cout<<"Detaching Thread "<<std::endl;
       threadObj.detach();
   }
   
   std::thread threadObj2( (WorkerThread()) );
   if(threadObj2.joinable())
   {
       std::cout<<"Joining Thread "<<std::endl;
       threadObj2.join();
   }
   if(threadObj2.joinable())    
   {
       std::cout<<"Joining Thread "<<std::endl;
       threadObj2.join();
   }

Case 2: Never forget to call either join or detach on a std::thread object with associated executing thread

In this case, if neither join nor detach is called with a ‘std::thread’ object that has associated executing thread then during that object’s destruct-or it will terminate the program.

#include <iostream>
#include <thread>
#include <algorithm>
class WorkerThread
{
public:
    void operator()()     
    {
        std::cout<<"Worker Thread "<<std::endl;
    }
};
int main()  
{
    std::thread threadObj( (WorkerThread()) );
    // Program will terminate as we have't called either join or detach with the std::thread object.
    // Hence std::thread's object destructor will terminate the program
    return 0;
}

Similarly, we should not forget to call either join() or detach() in case of exceptions.

To prevent this with we should use Resource Acquisition Is Initialization (RAII) which is show below,

#include <iostream>
#include <thread>
class ThreadRAII
{
    std::thread & m_thread;
    public:
        ThreadRAII(std::thread  & threadObj) : m_thread(threadObj)
        {
            
        }
        ~ThreadRAII()
        {
            // Check if thread is joinable then detach the thread
            if(m_thread.joinable())
            {
                m_thread.detach();
            }
        }
};
void thread_function()
{
    for(int i = 0; i < 10000; i++);
        std::cout<<"thread_function Executing"<<std::endl;
}
 
int main()  
{
    std::thread threadObj(thread_function);
    
    // If we comment this Line, then program will crash
    ThreadRAII wrapperObj(threadObj);
    return 0;
}

Conclusion:

In this article, we have discussed completely regarding C++11 Multithreading joining and detaching threads of std::thread and some risk cases. Thank you!

How to create a discord bot python – How to Make a Discord Bot Python

How to create a discord bot python: In a world where video games are so important to so many people, communication and community around games are vital. Discord offers both of those and more in one well-designed package. In this tutorial, you’ll learn how to make a Discord bot in Python so that you can make the most of this fantastic platform.

What Is Discord?

Discord bot python tutorial: Discord is a voice and text communication platform for gamers.

Players, streamers, and developers use Discord to discuss games, answer questions, chat while they play, and much more. It even has a game store, complete with critical reviews and a subscription service. It is nearly a one-stop shop for gaming communities.

While there are many things you can build using Discord’s APIs this tutorial will focus on a particular learning outcome: how to make a Discord bot in Python.

What Is a Bot?

Python discord bot tutorial: Discord is growing in popularity. As such, automated processes, such as banning inappropriate users and reacting to user requests are vital for a community to thrive and grow.

Automated programs that look and act like users and automatically respond to events and commands on Discord are called bot users. Discord bot users (or just bots) have nearly unlimited application.

How to Make a Discord Bot in the Developer Portal:

Before you can dive into any Python code to handle events and create exciting automations, you need to first create a few Discord components:

  1. An account
  2. An application
  3. A bot
  4. A guild

You’ll learn more about each piece in the following sections.

Once you’ve created all of these components, you’ll tie them together by registering your bot with your guild.

Creating a Discord Account

Create discord bot python: The first thing you’ll see is a landing page where you’ll need to either login, if you have an existing account, or create a new account:

Creating-a-Discord-Account

If you need to create a new account, then click on the Register button below Login and enter your account information.

Once you’re finished, you’ll be redirected to the Developer Portal home page, where you’ll create your application.

Creating-a-Discord-Account-login

Creating an Application:

How to make a discord bot with python: An application allows you to interact with Discord’s APIs by providing authentication tokens, designating permissions, and so on.

To create a new application, select New Application:

Creating-a-Discord-Account-application

Next, you’ll be prompted to name your application. Select a name and click Create:

Creating-a-Discord-Account-login-creating

Congratulations! You made a Discord application. On the resulting screen, you can see information about your application:

Creating-a-Discord-Account-login-done.png

Keep in mind that any program that interacts with Discord APIs requires a Discord application, not just bots. Bot-related APIs are only a subset of Discord’s total interface.

However, since this tutorial is about how to make a Discord bot, navigate to the Bot tab on the left-hand navigation list.

Creating a Bot

As you learned in the previous sections, a bot user is one that listens to and automatically reacts to certain events and commands on Discord.

For your code to actually be manifested on Discord, you’ll need to create a bot user. To do so, select Add Bot:

Creating-a-Discord-boat

Once you confirm that you want to add the bot to your application, you’ll see the new bot user in the portal:

Creating-a-Discord-account-new-boat-user

Now, the bot’s all set and ready to go, but to where?

A bot user is not useful if it’s not interacting with other users. Next, you’ll create a guild so that your bot can interact with other users.

Creating a Guild

A guild (or a server, as it is often called in Discord’s user interface) is a specific group of channels where users congregate to chat.

You’d start by creating a guild. Then, in your guild, you could have multiple channels, such as:

  • General Discussion: A channel for users to talk about whatever they want
  • Spoilers, Beware: A channel for users who have finished your game to talk about all the end game reveals
  • Announcements: A channel for you to announce game updates and for users to discuss them

Once you’ve created your guild, you’d invite other users to populate it.

So, to create a guild, head to your Discord home page:

Creating-a-Discord-home-page

From this home page, you can view and add friends, direct messages, and guilds. From here, select the + icon on the left-hand side of the web page to Add a Server:

This will present two options, Create a server and Join a Server. In this case, select Create a server and enter a name for your guild.

Creating-a-Discord-creating-a-server

Once you’ve finished creating your guild, you’ll be able to see the users on the right-hand side and the channels on the left.

The final step on Discord is to register your bot with your new guild.

Adding a Bot to a Guild

A bot can’t accept invites like a normal user can. Instead, you’ll add your bot using the OAuth2 protocol.

To do so, head back to the Developer Portal and select the OAuth2 page from the left-hand navigation:

Add your bot using the OAuth2 protocol.

From this window, you’ll see the OAuth2 URL Generator.

This tool generates an authorization URL that hits Discord’s OAuth2 API and authorizes API access using your application’s credentials.

In this case, you’ll want to grant your application’s bot user access to Discord APIs using your application’s OAuth2 credentials.

To do this, scroll down and select bot from the SCOPES options and Administrator from BOT PERMISSIONS:

BOT PERMISSIONS

Now, Discord has generated your application’s authorization URL with the selected scope and permissions.

Select Copy beside the URL that was generated for you, paste it into your browser, and select your guild from the dropdown options:

Creating-a-Discord-select-your-grid

Click Authorize, and you’re done!

 

Authorized
If you go back to your guild, then you’ll see that the bot has been added:

Bot added

In summary, you’ve created:

  • An application that your bot will use to authenticate with Discord’s APIs
  • A bot user that you’ll use to interact with other users and events in your guild
  • A guild in which your user account and your bot user will be active
  • ADiscordaccount with which you created everything else and that you’ll use to interact with your bot

Now, you know how to make a Discord bot using the Developer Portal. Next comes the fun stuff: implementing your bot in Python!

How to Make a Discord Bot in Python

Since you’re learning how to make a Discord bot with Python, you’ll be using discord.py.

discord.py is a Python library that exhaustively implements Discord’s APIs in an efficient and Pythonic way. This includes utilizing Python’s implementation of Async IO

Begin by installing discord.py with pip:

$ pip install -U discord.py

Now that you’ve installed discord.py, you’ll use it to create your first connection to Discord!

Creating a Discord Connection

The first step in implementing your bot user is to create a connection to Discord. With discord.py, you do this by creating an instance of Client:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

client.run(TOKEN)

A Client is an object that represents a connection to Discord. A Client handles events, tracks state, and generally interacts with Discord APIs.

Here, you’ve created a Client and implemented its on_ready() event handler, which handles the event when the Client has established a connection to Discord and it has finished preparing the data that Discord has sent, such as login state, guild and channel data, and more.

In other words, on_ready() will be called (and your message will be printed) once client is ready for further action. You’ll learn more about event handlers later in this article.

When you’re working with secrets such as your Discord token, it’s good practice to read it into your program from an environment variable. Using environment variables helps you:

  • Avoid putting the secrets into source control
  • Use different variables for development and production environments without changing your code

While you could export DISCORD_TOKEN={your-bot-token}, an easier solution is to save a .env file on all machines that will be running this code. This is not only easier, since you won’t have to export your token every time you clear your shell, but it also protects you from storing your secrets in your shell’s history.

Create a file named .env in the same directory as bot.py:

You’ll need to replace {your-bot-token} with your bot’s token, which you can get by going back to the Bot page on the Developer portal and clicking Copy under the TOKEN section:

 Creating-a-Discord-adding-bot-token

Looking back at the bot.py code, you’ll notice a library called dotnev. This library is handy for working with .env files. load_dotenv()loads environment variables from a .env file into your shell’s environment variables so that you can use them in your code.

Install dotenv with pip:

pip install -U python-dotenv

Finally, client.run() runs your Client using your bot’s token.

Now that you’ve set up both bot.py and .env, you can run your code:

python bot.py
Shikhaboat#5531 has connected to Discord!

Great! Your Client has connected to Discord using your bot’s token. In the next section, you’ll build on this Client by interacting with more Discord APIs.

Interacting With Discord APIs

Using a Client, you have access to a wide range of Discord APIs.

For example, let’s say you wanted to write the name and identifier of the guild that you registered your bot user with to the console.

First, you’ll need to add a new environment variable:

# .env
DISCORD_TOKEN={your-bot-token}
DISCORD_GUILD={your-guild-name}

Don’t forget that you’ll need to replace the two placeholders with actual values:

  1. {your-bot-token}
  2. {your-guild-name}

Remember that Discord calls on_ready(), which you used before, once the Client has made the connection and prepared the data. So, you can rely on the guild data being available inside on_ready():

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

Here, you looped through the guild data that Discord has sent client, namely client.guilds. Then, you found the guild with the matching name and printed a formatted string to stdout.

Run the program to see the results:

 python bot.py
Shikhaboat#5531 is connected to the following guild:
Shikhaboat#5531(id: 571759877328732195)

Great! You can see the name of your bot, the name of your server, and the server’s identification number.

Another interesting bit of data you can pull from a guild is the list of users who are members of the guild:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})\n'
    )

    members = '\n - '.join([member.name for member in guild.members])
    print(f'Guild Members:\n - {members}')

client.run(TOKEN)

By looping through guild.members, you pulled the names of all of the members of the guild and printed them with a formatted string.

When you run the program, you should see at least the name of the account you created the guild with and the name of the bot user itself:

$ python bot.py
Shikhaboat#5531 is connected to the following guild:
Shikhaboat#5531(id: 571759877328732195)
Guild Members:
 - aronq2
 - RealPythonTutorialBot

These examples barely scratch the surface of the APIs available on Discord, be sure to check out their documentation to see all that they have to offer.

Next, you’ll learn about some utility functions and how they can simplify these examples.

Using Utility Functions

Let’s take another look at the example from the last section where you printed the name and identifier of the bot’s guild:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

You could clean up this code by using some of the utility functions available in discord.py.

discord.utils.find is one utility that can improve the simplicity and readability of this code by replacing the for loop with an intuitive, abstracted function:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    guild = discord.utils.find(lambda g: g.name == GUILD, client.guilds)
    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

<find() takes a function, called a predicate, which identifies some characteristic of the element in the iterable that you’re looking for. Here, you used a particular type of anonymous function, called a lambda, as the predicate.

In this case, you’re trying to find the guild with the same name as the one you stored in the DISCORD_GUILD environment variable. Once find() locates an element in the iterable that satisfies the predicate, it will return the element. This is essentially equivalent to the break statement in the previous example, but cleaner.

discord.py has even abstracted this concept one step further with the get.utility():

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    guild = discord.utils.get(client.guilds, name=GUILD)
    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

get() takes the iterable and some keyword arguments. The keyword arguments represent attributes of the elements in the iterable that must all be satisfied for get() to return the element.

In this example, you’ve identified name=GUILD as the attribute that must be satisfied.

Now that you’ve learned the basics of interacting with APIs, you’ll dive a little deeper into the function that you’ve been using to access them: on_ready().

Responding to Events

You already learned that on_ready() is an event. In fact, you might have noticed that it is identified as such in the code by the client.event decorator.

But what is an event?

An event is something that happens on Discord that you can use to trigger a reaction in your code. Your code will listen for and then respond to events.

Using the example you’ve seen already, the on_ready() event handler handles the event that the Client has made a connection to Discord and prepared its response data.

So, when Discord fires an event, discord.py will route the event data to the corresponding event handler on your connected Client.

There are two ways in discord.py to implement an event handler:

  1. Using the client.event decorator
  2. Creating a subclass of Client and overriding its handler methods

You already saw the implementation using the decorator. Next, take a look at how to subclass Client:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

class CustomClient(discord.Client):
    async def on_ready(self):
        print(f'{self.user} has connected to Discord!')

client = CustomClient()
client.run(TOKEN)

Here, just like before, you’ve created a client variable and called <.run() with your Discord token. The actual Client is different, however. Instead of using the normal base class, client is an instance of CustomClient, which has an overridden on_ready() function.

There is no difference between the two implementation styles of events, but this tutorial will primarily use the decorator version because it looks similar to how you implement Bot commands, which is a topic you’ll cover in a bit.

Welcoming New Members

Previously, you saw the example of responding to the event where a member joins a guild. In that example, your bot user could send them a message, welcoming them to your Discord community.

Now, you’ll implement that behavior in your Client, using event handlers, and verify its behavior in Discord:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user.name} has connected to Discord!')

@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Hi {member.name}, welcome to my Discord server!'
    )

client.run(TOKEN)

Like before, you handled the on_ready() event by printing the bot user’s name in a formatted string. New, however, is the implementation of the on_member_join() event handler.

on_member_join(), as its name suggests, handles the event of a new member joining a guild.

In this example, you used member.create_dm()to create a direct message channel. Then, you used that channel to send() a direct message to that new member.

Now, let’s test out your bot’s new behavior.

First, run your new version of bot.py and wait for the on_ready() event to fire, logging your message to stdout:

$ python bot.py
ShikhaBot has connected to Discord!

Now, head over to Discord, log in, and navigate to your guild by selecting it from the left-hand side of the screen:

Creating-a-Discord-navigate-to-server

Select Invite People just beside the guild list where you selected your guild. Check the box that says Set this link to never expire and copy the link:

InvitePepole

Now, with the invite link copied, create a new account and join the guild using your invite link.

First, you’ll see that Discord introduced you to the guild by default with an automated message. More importantly though, notice the badge on the left-hand side of the screen that notifies you of a new message:

 Creating-a-Discord-account-new-message.
When you select it, you’ll see a private message from your bot user:

 Boat-is-created

Perfect! Your bot user is now interacting with other users with minimal code.

Conclusion

Congratulations! Now, you’ve learned how to make a Discord bot in Python. You’re able to build bots for interacting with users in guilds that you create or even bots that other users can invite to interact with their communities.

 

Pthread_detach example – POSIX: Detached vs Joinable threads | pthread_join() & pthread_detach() Examples

POSIX- Detached vs Joinable threads, pthread_join() & pthread_detach() Examples

Pthread_detach example: Guys who are looking for the perfect guide or tutorial for POSIX: Detached vs Joinable threads and pthread_join() & pthread_detach() examples? Can stay with us. This tutorial will explain & give you complete guidance while programming by using these Detached & Joinable Threads. Before going to learn Detached vs Joinable threads along with pthread_join() & pthread_detach() examples let’s start understanding what is thread and pthread?

About threads

Pthread_join examples: A thread is a semi-process that has its own stack and executes a given piece of code. threads within the same process run in shared memory space, it defined as an independent stream of instructions that can be scheduled to run as such by the operating system.

What is pthreads?

Pthread_detach: POSIX Threads usually referred to as pthreads, is an execution model that exists independently from a language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time.

Thread can be run in two modes. They are as such,

1. Joinable mode
2. Detached mode

Joinable Thread & pthread_join()

Pthread_join example: A joinable thread will not release any resource even after the end of the thread function until some other thread calls pthread_join() with its ID.

Whereas pthread_join() is a blocking call, it will block the calling thread until the other thread ends.

We will pass two parameters in pthread-

1. The ID of the target thread

2. Address of (void *) i.e. (void **), it will point to the return value of thread function i.e. pointer to (void *).

pthread_join() will return non-zero value in case of error.

Example of pthread_join()

Pthread_join(): Below is the example for joinable thread,

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
void * threadFunc(void * arg)
{
    std::cout << "Thread Function :: Start" << std::endl;
    // Sleep for 2 seconds
    sleep(2);
    std::cout << "Thread Function :: End" << std::endl;
    // Return value from thread
    return new int(6);
}
int main()
{
    // Thread id
    pthread_t threadId;
    // Create a thread that will funtion threadFunc()
    int err = pthread_create(&threadId, NULL, &threadFunc, NULL);
    // Check if thread is created sucessfuly
    if (err)
    {
        std::cout << "Thread creation failed : " << strerror(err);
        return err;
    }
    else
        std::cout << "Thread Created with ID : " << threadId << std::endl;
    // Do some stuff
    void * ptr = NULL;
    std::cout << "Waiting for thread to exit" << std::endl;
    // Wait for thread to exit
    err = pthread_join(threadId, &ptr);
    if (err)
    {
        std::cout << "Failed to join Thread : " << strerror(err) << std::endl;
        return err;
    }
    if (ptr)
        std::cout << " value returned by thread : " << *(int *) ptr
                << std::endl;
    delete (int *) ptr;
    return 0;
}

Output:

Thread Created with ID : 1407020804273336
Waiting for thread to exit
Thread Function :: Start
Thread Function :: End
value returned by thread : 6

Also Check:

Detached Thread & pthread_detach()

Pthread_detach: By default all threads are joinable, we will call pthread_detach() so to make a thread detached. A Detached thread automatically releases its allocated resources on exit. No other thread needs to join it.

#include <pthread.h>

int pthread_detach(pthread_t thread);

There is no way to determine its return value of the detached thread function.
pthread_detach() will return non zero value in case of error.

Output can change on your system because both the main and thread functions are running in parallel.

If the main function exits then all other threads will be exited.

pthread_detach() Example

Below is the example,

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
void * threadFunc(void * arg)
{
    std::cout << "Thread Function :: Start" << std::endl;
    std::cout << "Thread Function :: End" << std::endl;
    // Return value from thread
    return NULL;
}
int main()
{
    // Thread id
    pthread_t threadId;
    // Create a thread that will funtion threadFunc()
    int err = pthread_create(&threadId, NULL, &threadFunc, NULL);
    // Check if thread is created sucessfuly
    if (err)
    {
        std::cout << "Thread creation failed : " << strerror(err);
        return err;
    }
    else
        std::cout << "Thread Created with ID : " << threadId << std::endl;
    // Do some stuff
    err = pthread_detach(threadId);
    if (err)
        std::cout << "Failed to detach Thread : " << strerror(err) << std::endl;
    // Sleep for 2 seconds because if main function exits, then other threads will
    // be also be killed. Sleep for 2 seconds, so that detached exits by then
    sleep(2);
    std::cout << "Main function ends " << std::endl;
    return 0;
}

Output:

Thread Created with ID : 139703273027328
Thread Function :: Start
Thread Function :: End
Main function ends