Python скрипт
Python Scripts
Python scripts are files containing Python code that can be executed directly. They allow you to automate tasks, process data, build applications, and much more. This article covers the basics of Python scripts and how to work with them.
What is a Python Script?
A Python script is a file with a
.py
- Save your code for future use
- Execute multiple commands in sequence
- Create reusable programs
- Automate repetitive tasks
Creating a Python Script
To create a Python script:
- Open a text editor (like Notepad, VS Code, PyCharm, etc.)
- Write your Python code
- Save the file with a extension (e.g.,
.py
)my_script.py
Here's a simple example of a Python script:
# This is a simple Python script
print("Hello, World!")
# Calculate and display the sum of two numbers
a = 5
b = 7
sum_result = a + b
print(f"The sum of {a} and {b} is {sum_result}")
Running Python Scripts
There are several ways to run Python scripts:
From the Command Line
python my_script.py
Or on some systems:
python3 my_script.py
From an IDE
Most Python IDEs (like PyCharm, VS Code, IDLE) have a "Run" button or keyboard shortcut to execute scripts.
Making Scripts Executable (Unix/Linux/Mac)
-
Add a shebang line at the top of your script:
#!/usr/bin/env python3
-
Make the script executable:
chmod +x my_script.py
-
Run directly:
./my_script.py
Command-Line Arguments
Python scripts can accept command-line arguments using the
sys
import sys
# The first element (sys.argv[0]) is the script name
# The remaining elements are the arguments passed to the script
if len(sys.argv) > 1:
print(f"Arguments provided: {sys.argv[1:]}")
else:
print("No arguments provided")
Script Structure Best Practices
A well-structured Python script typically follows this pattern:
#!/usr/bin/env python3
"""
Description of what the script does.
"""
# Import statements
import sys
import os
import other_modules
# Constants
DEFAULT_VALUE = 100
CONFIG_FILE = "config.ini"
# Function definitions
def main():
"""Main function that runs when the script is executed."""
# Script logic here
print("Running main function")
def helper_function():
"""A function that helps with a specific task."""
return "Helper result"
# Main script execution
if __name__ == "__main__":
main()
The
if __name__ == "__main__":
Common Use Cases for Python Scripts
- Data processing and analysis
- Automation of repetitive tasks
- Web scraping
- File operations (renaming, organizing, etc.)
- System administration tasks
- Simple web servers or applications
- API interactions
- Database operations
Python scripts are versatile and can be used for virtually any programming task, from simple utilities to complex applications.