Movatterモバイル変換


[0]ホーム

URL:


Menu
×
Sign In
+1 Get Certified For Teachers Spaces Plus Get Certified For Teachers Spaces Plus
   ❮     
     ❯   

Python Tutorial

Python HOMEPython IntroPython Get StartedPython SyntaxPython CommentsPython VariablesPython Data TypesPython NumbersPython CastingPython StringsPython BooleansPython OperatorsPython ListsPython TuplesPython SetsPython DictionariesPython If...ElsePython MatchPython While LoopsPython For LoopsPython FunctionsPython LambdaPython ArraysPython OOPPython Classes/ObjectsPython InheritancePython IteratorsPython PolymorphismPython ScopePython ModulesPython DatesPython MathPython JSONPython RegExPython PIPPython Try...ExceptPython String FormattingPython User InputPython VirtualEnv

File Handling

Python File HandlingPython Read FilesPython Write/Create FilesPython Delete Files

Python Modules

NumPy TutorialPandas TutorialSciPy TutorialDjango Tutorial

Python Matplotlib

Matplotlib IntroMatplotlib Get StartedMatplotlib PyplotMatplotlib PlottingMatplotlib MarkersMatplotlib LineMatplotlib LabelsMatplotlib GridMatplotlib SubplotMatplotlib ScatterMatplotlib BarsMatplotlib HistogramsMatplotlib Pie Charts

Machine Learning

Getting StartedMean Median ModeStandard DeviationPercentileData DistributionNormal Data DistributionScatter PlotLinear RegressionPolynomial RegressionMultiple RegressionScaleTrain/TestDecision TreeConfusion MatrixHierarchical ClusteringLogistic RegressionGrid SearchCategorical DataK-meansBootstrap AggregationCross ValidationAUC - ROC CurveK-nearest neighbors

Python DSA

Python DSALists and ArraysStacksQueuesLinked ListsHash TablesTreesBinary TreesBinary Search TreesAVL TreesGraphsLinear SearchBinary SearchBubble SortSelection SortInsertion SortQuick SortCounting SortRadix SortMerge Sort

Python MySQL

MySQL Get StartedMySQL Create DatabaseMySQL Create TableMySQL InsertMySQL SelectMySQL WhereMySQL Order ByMySQL DeleteMySQL Drop TableMySQL UpdateMySQL LimitMySQL Join

Python MongoDB

MongoDB Get StartedMongoDB Create DBMongoDB CollectionMongoDB InsertMongoDB FindMongoDB QueryMongoDB SortMongoDB DeleteMongoDB Drop CollectionMongoDB UpdateMongoDB Limit

Python Reference

Python OverviewPython Built-in FunctionsPython String MethodsPython List MethodsPython Dictionary MethodsPython Tuple MethodsPython Set MethodsPython File MethodsPython KeywordsPython ExceptionsPython Glossary

Module Reference

Random ModuleRequests ModuleStatistics ModuleMath ModulecMath Module

Python How To

Remove List DuplicatesReverse a StringAdd Two Numbers

Python Examples

Python ExamplesPython CompilerPython ExercisesPython QuizPython ServerPython SyllabusPython Study PlanPython Interview Q&APython BootcampPython CertificatePython Training

PythonVirtual Environment


What is a Virtual Environment?

Avirtual environment in Python is an isolated environment on your computer, where you can run and test your Python projects.

It allows you to manage project-specific dependencies without interfering with other projects or the original Python installation.

Think of a virtual environment as a separate container for each Python project. Each container:

  • Has its own Python interpreter
  • Has its own set of installed packages
  • Is isolated from other virtual environments
  • Can have different versions of the same package

Using virtual environments is important because:

  • It prevents package version conflicts between projects
  • Makes projects more portable and reproducible
  • Keeps your system Python installation clean
  • Allows testing with different Python versions

Creating a Virtual Environment

Python has the built-invenv module for creating virtual environments.

To create a virtual environment on your computer, open the command prompt, and navigate to the folder where you want to create your project, then type this command:

Example

Run this command to create a virtual environment namedmyfirstproject:

C:\Users\Your Name> python -m venv myfirstproject
$ python -m venv myfirstproject

This will set up a virtual environment, and create a folder named "myfirstproject" with subfolders and files, like this:

Result

The file/folder structure will look like this:

myfirstproject
  Include
  Lib
  Scripts
  .gitignore
  pyvenv.cfg

Activate Virtual Environment

To use the virtual environment, you have to activate it with this command:

Example

Activate the virtual environment:

C:\Users\Your Name> myfirstproject\Scripts\activate
$ source myfirstproject/bin/activate

After activation, your prompt will change to show that you are now working in the active environment:

Result

The command line will look like this when the virtual environment is active:

(myfirstproject) C:\Users\Your Name>
(myfirstproject) ... $


Install Packages

Once your virtual environment is activated, you can install packages in it, usingpip.

We will install a package called 'cowsay':

Example

Install 'cowsay' in the virtual environment:

(myfirstproject) C:\Users\Your Name> pip install cowsay
(myfirstproject) ... $ pip install cowsay

Result

'cowsay' is installed only in the virtual environment:

Collecting cowsay
  Downloading cowsay-6.1-py3-none-any.whl.metadata (5.6 kB)
Downloading cowsay-6.1-py3-none-any.whl (25 kB)
Installing collected packages: cowsay
Successfully installed cowsay-6.1

[notice] A new release of pip is available:25.0.1 ->25.1.1
[notice] To update, run:python.exe -m pip install --upgrade pip

Using Package

Now that the 'cowsay' module is installed in your virtual environment, lets use it to display a talking cow.

Create a file calledtest.py on your computer. You can place it wherever you want, but I will place it in the same location as themyfirstproject folder -not in the folder, but in the same location.

Open the file and insert these three lines in it:

Example

Insert two lines intest.py:

import cowsay

cowsay.cow("Good Mooooorning!")

Then, try to execute the file while you are in the virtual environment:

Example

Executetest.py in the virtual environment:

(myfirstproject) C:\Users\Your Name> python test.py
(myfirstproject) ... $ python test.py

As a result a cow will appear in you terminal:

Result

The purpose of the 'cowsay' module is to draw a cow that says whatever input you give it:

  _________________| Good Mooooorning! |  =================                 \                  \                    ^__^                    (oo)\_______                    (__)\       )\/\                        ||----w |                        ||     ||

Deactivate Virtual Environment

To deactivate the virtual environment use this command:

Example

Deactivate the virtual environment:

(myfirstproject) C:\Users\Your Name> deactivate
(myfirstproject) ... $ deactivate

As a result, you are now back in the normal command line interface:

Result

Normal command line interface:

C:\Users\Your Name>
$

If you try to execute thetest.py file outside of the virtual environment, you will get an error because 'cowsay' is missing.It was only installed in the virtual environment:

Example

Executetest.py outside of the virtual environment:

C:\Users\Your Name> python test.py
$ python test.py

Result

Error because 'cowsay' is missing:

Traceback (most recent call last):
  File"C:\Users\Your Name\test.py", line1, in<module>
    import cowsay
ModuleNotFoundError:No module named 'cowsay'

Note: The virtual environmentmyfirstproject still exists, it is just not activated. If you activate the virtual environment again, you can execute thetest.py file, and the diagram will be displayed.


Delete Virtual Environment

Another nice thing about working with a virtual environment is that when you, for some reason want to delete it,there are no other projects depend on it, and only the modules and files in the specified virtual environment are deleted.

To delete a virtual environment, you can simply delete its folder with all its content. Either directly in the file system, or use the command line interface like this:

Example

Deletemyfirstproject from the command line interface:

C:\Users\Your Name> rmdir /s /q myfirstproject
$ rm -rf myfirstproject


 
Track your progress - it's free!
 

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp