Virtual Environment For My First Python Program

 

Here We will create a virtual environment and code inside the environment.
So why virtual Environment?

  • to separate and isolate the packages we are using for different programs and projects.
  • working with code that depends on different versions of some library.
  • This issue happens a lot when dealing with Python 2 and Python 3.
  • Having different versions of packages installed can lead to a lot of confusion and bugs.

It’s much better to have separate environments for separate programs.

The module we use to create virtual environment here is called venv.

  • venv will install most recent version of python that is available.

To create a virtual environment, We have to decide upon a directory where we want to place it. And run venv module as script with directory path.

  • Suppose we want to create a virtual environment at home/dev:
    then change directory to the path as follows

     $cd home/dev
    

Now inside the directory we will run venv script:

     ~/dev$ python -m venv python-dev

What this does is:

  • creates python-dev directory if it doesn't exist
  • also creates directories inside it containing a copy of the python interpreter, the standard library and various supporting files.

Once we have created Virtual Environment, We have to activate it.

  • Run following command
    On Windows:

     python-dev\scripts\activate
    

    Here, extension for activate file should be mentioned whether its .bat for cmd or .ps1 for Power shell.
    In cmd,

     Scripts\activate.bat
    

and in PowerShell,

     Scripts\Activate.ps1

Updated through comment
on Linux or Mac:

     source python-dev/bin/activate

After activating, we can start programming.
now create main.py file.

  • if you have vs code installed then you can simply type code main.py in your terminal.

     ~/dev/python-dev $ code main.py
    

This opens a main.py file in vscode editor.
Now we can code our first Python Program Here.

     def main():
         print("hello world!")
     if __name__=="__main__":
         main() 
     else:
         print("file invoked")
 

 
Mausam ... Welcome to WhatsApp chat
How can we help you today?
Type here...