Skip to content

Commit b9e49aa

Browse files
authored
Create README.md
1 parent 34d3805 commit b9e49aa

File tree

1 file changed

+227
-0
lines changed

1 file changed

+227
-0
lines changed
+227
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
# Python Code Editor & Executor
2+
3+
This is a web-based Python code editor built using PyWebIO. The editor allows users to write and execute Python code in a web interface. It also offers customization options for themes and fonts to enhance the coding experience.
4+
5+
## Features
6+
7+
- **Code Execution**: Write and execute Python code directly in the browser.
8+
- **Customization**: Choose from a variety of themes and font families.
9+
- **Error Handling**: Displays standard output and error messages.
10+
- **History Management**: Retains the history of executed code snippets.
11+
- **Clear Output**: Option to clear the output area.
12+
13+
## Setup and Installation
14+
15+
To run this project locally, follow these steps:
16+
17+
1. **Clone the repository:**
18+
19+
20+
`git clone https://github.com/JawadSher/Python-Projects-Beginner-to-Advance/tree/main/Project%2011%20-%20Python%20Code%20Editor`
21+
22+
2. **Navigate to the project directory:**
23+
24+
25+
`cd your-repo-name`
26+
27+
3. **Install the required packages:**
28+
29+
30+
`pip install pywebio`
31+
32+
4. **Start the server:**
33+
34+
35+
`python main.py`
36+
37+
5. Open your browser and navigate to `http://localhost:8080` to access the editor.
38+
39+
40+
## Usage
41+
42+
1. **Customization:**
43+
44+
- Select your preferred theme from the dropdown menu.
45+
- Choose a font family.
46+
- Specify the font size (default is 18px).
47+
2. **Code Editor:**
48+
49+
- Write your Python code in the provided text area.
50+
- Click the "Run" button to execute the code.
51+
3. **Output:**
52+
53+
- View the standard output and error messages in the output section.
54+
- Use the "Clear" button to clear the output area.
55+
56+
## Code Explanation
57+
58+
### Imports and Dependencies
59+
60+
python
61+
62+
Copy code
63+
64+
```
65+
from pywebio.input import textarea, select, input, NUMBER
66+
from pywebio.output import put_html, put_text, use_scope, put_error, put_code, put_button, clear
67+
from pywebio import start_server
68+
import io
69+
import sys
70+
```
71+
72+
These are the necessary imports from the PyWebIO library and the standard `io` and `sys` modules for input/output redirection. The `pywebio.input` and `pywebio.output` modules are used for creating the user interface elements and displaying output respectively. The `start_server` function is used to run the web server.
73+
74+
### Function: `execute_code`
75+
76+
77+
```
78+
def execute_code(code):
79+
o_stdout = sys.stdout
80+
o_stderr = sys.stderr
81+
82+
redirected_stdout = sys.stdout = io.StringIO()
83+
redirected_stderr = sys.stderr = io.StringIO()
84+
85+
try:
86+
exec_global = {}
87+
exec(code, exec_global)
88+
return redirected_stdout.getvalue(), redirected_stderr.getvalue()
89+
except Exception as e:
90+
return "", f"Error Executing Code: {e}"
91+
finally:
92+
sys.stdout = o_stdout
93+
sys.stderr = o_stderr
94+
```
95+
96+
This function captures the standard output and error messages when executing Python code. It works as follows:
97+
98+
1. **Redirect stdout and stderr**: `sys.stdout` and `sys.stderr` are redirected to `io.StringIO()` objects to capture the output and error messages.
99+
2. **Execute Code**: The `exec` function executes the provided Python code within an isolated dictionary `exec_global` to avoid polluting the global namespace.
100+
3. **Return Output and Errors**: Captured output and error messages are returned as strings.
101+
4. **Restore stdout and stderr**: Finally, `sys.stdout` and `sys.stderr` are restored to their original values to avoid affecting other parts of the program.
102+
103+
### Function: `customization`
104+
105+
106+
107+
```
108+
def customization():
109+
theme_options = [
110+
"default dark+",
111+
"default light+",
112+
"quiet light",
113+
"solarized dark",
114+
"solarized light",
115+
"monokai",
116+
"dark (Visual Studio)",
117+
"light (Visual Studio)",
118+
"dark+ (Contrast)",
119+
"kimbie dark",
120+
"darcula",
121+
]
122+
123+
font_options = [
124+
"Ubuntu Mono",
125+
"Fira Code",
126+
"monospace",
127+
"Consolas",
128+
"Roboto Mono",
129+
"Inconsolata",
130+
"Source Code Pro",
131+
"Courier New",
132+
"Hack",
133+
"Cascadia Code"
134+
]
135+
136+
theme = select("Select Theme", options=theme_options)
137+
font = select("Select Font Family", options=font_options)
138+
font_num = input('Select Font Size', type=NUMBER, placeholder='Default 18px')
139+
140+
return theme, font, font_num
141+
```
142+
143+
This function provides customization options for selecting a theme, font family, and font size:
144+
145+
1. **Theme Options**: A list of available themes is provided in `theme_options`.
146+
2. **Font Options**: A list of available font families is provided in `font_options`.
147+
3. **User Input**: The `select` function is used to create dropdown menus for theme and font family selection, and the `input` function is used for font size input.
148+
4. **Return Values**: The selected theme, font family, and font size are returned.
149+
150+
### Function: `main`
151+
152+
153+
```
154+
def main():
155+
put_html("""
156+
<style>
157+
.app-title {
158+
font-size: 36px;
159+
font-weight: bold;
160+
color: #247ba0;
161+
text-align: center;
162+
margin-bottom: 20px;
163+
}
164+
</style>
165+
<h1 class="app-title">Python Code Editor</h1>
166+
""")
167+
168+
theme_name, font_family, font_size = customization()
169+
170+
put_html(f"""
171+
<style>
172+
.CodeMirror {{
173+
font-size: {font_size}px !important;
174+
font-family: '{font_family}', monospace;
175+
line-height: 1.5;
176+
background-color: var(--vscode-{theme_name.replace(' ', '').lower()}-background);
177+
color: var(--vscode-{theme_name.replace(' ', '').lower()}-foreground);
178+
}}
179+
</style>
180+
""")
181+
182+
c_history = {}
183+
184+
while True:
185+
code = textarea('Enter Python code', code={
186+
'rows': 20,
187+
'required': True,
188+
'mode': 'python',
189+
'theme': f'{theme_name}',
190+
'placeholder': 'Type your Python code here'
191+
})
192+
193+
if code.strip():
194+
if code not in c_history:
195+
c_history[code] = (None, None)
196+
stdout, stderr = execute_code(code)
197+
c_history[code] = (stdout, stderr)
198+
else:
199+
stdout, stderr = c_history[code]
200+
201+
with use_scope('output', clear=True):
202+
put_html("<b>Source Code:</b>")
203+
put_code(code, language='python')
204+
if stdout:
205+
put_html("<b>Standard Output:</b>")
206+
put_text(stdout)
207+
if stderr:
208+
put_html("<b>Standard Error:</b>")
209+
put_error(stderr)
210+
211+
if stdout or stderr:
212+
put_button('Clear', onclick=lambda: clear(scope='output'))
213+
else:
214+
put_html("<b>Error:</b> Please enter some Python code.")
215+
```
216+
217+
This is the main function that runs the PyWebIO application. It sets up the HTML and CSS for the interface, collects customization options, and processes the user's Python code:
218+
219+
1. **Title Styling**: The `put_html` function is used to style the title of the application.
220+
2. **Customization**: The `customization` function is called to get the user's theme, font family, and font size preferences.
221+
3. **Apply Customization**: The selected theme, font family, and font size are applied to the code editor using inline CSS.
222+
4. **Code Execution Loop**: A loop is used to continuously accept and execute code from the user.
223+
- **Textarea**: The `textarea` function creates an input area for the user to write Python code.
224+
- **Code History**: A dictionary `c_history` is used to store the history of executed code snippets and their outputs.
225+
- **Execute Code**: The `execute_code` function is called to run the user's code and capture the output and errors.
226+
- **Display Output**: The output and error messages are displayed using the `put_html`, `put_text`, `put_error`, and `put_code` functions.
227+
- **Clear Output**: A "Clear" button is provided to clear the output area.

0 commit comments

Comments
 (0)