r/pythoncoding • • Nov 23 '25

Python Terminal

0 Upvotes

I've made a python script type device before named CodeByte but I'm looking into making a 2nd script named TerminOS. I've started development and it auto checks pip versions, can install pip packages, and read and write files all in the terminal! Before I finish up I'm wondering if anyone has anymore command ideas.


r/pythoncoding • • Jul 02 '22

How to create classes without the class keyword

7 Upvotes

In Python, we learn that in order to create a class you need to start off with the `class` keyword. But the reality is that we actually don't.

I've written an article on how this works. We take a deeper dive into data types in Python and explore how they work under the hood.

I explore how all data types are classes, and how they can all be derived from `type` which by the way can do more than tell you the type of an object! Check out the article below if this sounds intriguing.

https://medium.com/@Salaah01/creating-a-class-in-python-without-the-class-keyword-67ce84bae22


r/pythoncoding • • Apr 23 '26

I created an OS in Python

Thumbnail
github.com
8 Upvotes

I made an OS in Python. I used Kivy for UI and apps. It features multiple built in apps including Files, Settings, and an Appstore. Using the Appstore you can install other apps. It also features its own file system (inside the OS folder). Theres tons of other features to come, but if you to try it out, go to the attached link.


r/pythoncoding • • Apr 05 '23

The best explanation for creating different virtual environment at Python

4 Upvotes

This is by far the best explanation for creating different virtual environment at Python. This goes over conda, venv, and virtualenv.

https://youtu.be/MF7asKblfm8


r/pythoncoding • • Aug 09 '26

Why Leave Your Editor? Microsoft Dev Tunnels vs. ngrok in 2026

0 Upvotes

Developers exposing a local server to the internet used to mean one thing: download a CLI, create an account, paste an authtoken, and bounce between your editor and a separate terminal window. Microsoft has spent the last few years narrowing that gap by building port forwarding directly into VS Code’s Ports view, backed by its Dev Tunnels service. No extension required, no separate binary - just a right-click in a panel you already have open. Read the complete article here - https://instatunnel.my/blog/why-leave-your-editor-microsoft-dev-tunnels-vs-ngrok-in-2026

That doesn’t make ngrok obsolete. It makes the choice more interesting, because the two tools have converged on similar free-tier shapes while staying different in what they’re actually built for. This piece breaks down where Dev Tunnels genuinely wins, where the popular narrative about ngrok’s free tier is outdated, and where ngrok remains the only real option.

The Cost of Context Switching

Local development in the early 2020s was fragmented: write code in VS Code, run the app in the integrated terminal, then open a second terminal to run a tunneling tool for a public HTTPS URL. Every time you needed to test a Stripe webhook or share a preview link, you left your editor, checked whether your auth token had expired, and copy-pasted URLs into someone else’s dashboard.

VS Code’s Ports view collapses that into one place. If your app is already running in the integrated terminal, forwarding a port takes a right-click, not a new tool.


r/pythoncoding • • Sep 10 '15

PEP 0989 Approved

Thumbnail
python.org
0 Upvotes

r/pythoncoding • • Jul 04 '24

Python AI Coder celebrates Independents Day, by coding fireworks display, in 3 minutes

Thumbnail
youtu.be
0 Upvotes

r/pythoncoding • • Jul 29 '22

A python script that generates a python-like script

2 Upvotes

I made this because, for reasons I don't have time to go into, I needed to leave my computer on and unlocked while my Reddit bots were running. I wanted to discourage non-coders from interfering with my computer, so I thought of having infinitely generated important-looking code run down my screen to make people think twice about it.

I thought that someone else had probably made something similar, possibly even better, before, but I wanted to do this myself. I thought maybe other people might like to use this in any way they like, so I'm making it publicly available here. If you can think of a subreddit this better belongs in, please comment.

It requires the libraries 'os', 'random', 'time' and 'termcolor'. I ran it in an emulated console within pycharm.

Code (tutorial in comments):

# Import all relevant libraries

# For clearing the console, if necessary
from os import system, name
# I use randomization a lot in this script!
from random import randint
# Mostly for waiting a bit between printing lines to make it feel more real
from time import sleep
# For syntax highlighting
from termcolor import colored


# Create the clear console function
def clearConsole():
    system('cls' if name == 'nt' else 'clear')

# Create the 'random comparison' function. (For creating a line of code along the lines of 'x < 3')
def getRandomComparison():
    # Reset the variable that I will be appending text to
    random_comparison = ''
    # Append the original 'x/y' to check comparison of
    random_comparison += colored(['x', 'y', 'i'][randint(0, 2)], 'red') + ' '
    # Check if it's an 'in' operator
    if randint(0, 6) == 0:
        # Check if it's in a random list
        random_comparison += colored('in ', 'green') + colored(['x', 'y'][randint(0, 1)], 'red')
    else:
        # Add comparison part
        random_comparison += ['==', '<=', '>=', '<', '>'][randint(0, 4)] + ' '
        # Append the value you are comparing it to
        random_comparison += [colored('x', 'red'), colored('y', 'red'), colored(str(randint(-100, 200)), 'magenta'), colored(str(randint(-10000, 20000) / 100), 'magenta')][randint(0, 3)]
    # Return random comparison
    return random_comparison

# Create random function name function
def createRandomFunctionName():
    # Reset random function name variable that I will be appending to
    random_function_name = ''
    # Set up lists to randomly select data from
    term_1_words = ['set', 'addTo', 'scribble', 'turtle', 'change', 'lengthOf', 'radius', 'let', 'if', 'control', 'create']
    term_2_words = ['X', 'Y', 'Turtles', 'Radius', 'Length', 'Variable', 'Notch', 'OurMotto', 'Peacocks', 'Pterodactyls', 'Carrots']
    term_3_words = ['ByTen', 'Immediately', 'Red', 'AllOver', 'Iterative', 'Gradually', 'AtLength']
    # Select data randomly
    random_function_name += term_1_words[randint(0, len(term_1_words) - 1)]
    random_function_name += term_2_words[randint(0, len(term_2_words) - 1)]
    random_function_name += term_3_words[randint(0, len(term_3_words) - 1)]
    random_function_name += '()'
    # Return random function name
    return colored(random_function_name, 'green')

# In about 'var' many lines, 1 of them will open/close a loop. I recommend making the chance of opening loops smaller than the chance of closing them.
chance_of_opening_loops = 4
chance_of_closing_loops = 6

# Set data for operators that may be used later on
loop_code_list = ['for', 'while', 'if', 'def']
code_options_list = ['print', 'sleep']

# Indentation starts at 0, but can be increased later on randomly
indentation = 0
# This will now generate code forever, or until you stop the script
while True:
    # Randomize line of code

    # Reset the line of code variable, which will be appended to later
    line_of_code = ''

    # Randomly decide if this line of code will open a loop
    line_opens_a_loop = False
    if randint(0, chance_of_opening_loops) == 0:
        line_opens_a_loop = True

    # If code opens a loop
    if line_opens_a_loop and indentation <= 26:
        # Get random operator from the list of loop operators
        operator = loop_code_list[randint(0, len(loop_code_list) - 1)]
        # Append operator name to line of code
        line_of_code += colored(operator, 'green') + ' '

        # Different randomizers for different operators
        if operator == 'while':
            # Check if it's a simple boolean
            if randint(0, 1) == 0:
                # Append True or False to line of code
                line_of_code += colored(['True', 'False'][randint(0, 1)], 'yellow')
            else:
                # Append a random comparison, defined earlier, to the line of code
                line_of_code += getRandomComparison()

        # When operator is 'if'
        elif operator == 'if':
            # Append a random comparison, defined earlier, to the line of code
            line_of_code += getRandomComparison()

        # When operator is 'for'
        elif operator == 'for':
            # Append random variable (x/y/i) to line of code
            line_of_code += colored(['x', 'y', 'i'][randint(0, 2)], 'red') + ' '
            # Append a random comparison to line of code
            line_of_code += ['<=', '>=', '<', '>'][randint(0, 3)] + ' '
            # Append a random number to line of code (the number for the comparison to compare to)
            line_of_code += colored([str(randint(-100, 200)), str(randint(-10000, 20000) / 100)][randint(0, 1)], 'magenta')

        # When operator is 'def'
        elif operator == 'def':
            # Append random function name to the 'def' line
            line_of_code += createRandomFunctionName()
        else:
            # If it somehow isn't any of these, just append 'True' to line of code
            line_of_code += colored('True', 'yellow')

        # Add ':' to the end of the loop line, as it is indeed a loop
        line_of_code += ':'

    # If the line of code does not open a loop
    else:
        # Check if operator is an '=' command, if not:
        if randint(0, 3) == 0:
            # Make operator a random item from the list of non loop operators
            operator = code_options_list[randint(0, len(code_options_list) - 1)]
            # Append operator name to line of code
            line_of_code += colored(operator, 'green')

            # Different commands based on operator, if it is 'sleep':
            if operator == 'sleep':
                # Add a random amount of time to the sleep command
                line_of_code += '(' + colored([str(randint(1, 15)), str(randint(1, 99) / 100)][randint(0, 1)], 'magenta') + ')'

            # If it is 'print'
            elif operator == 'print':
                # Open brackets
                line_of_code += '('
                # If it prints a word
                if randint(0, 1) == 0:
                    # Define word data (I was a bit lazy here)
                    word_parts_1 = ['big', 'happy']
                    word_parts_2 = ['customers', 'lullabies']
                    # Add random words to line of code
                    line_of_code += colored('\'' + word_parts_1[randint(0, len(word_parts_1) - 1)] + ['', ' '][randint(0, 1)] + word_parts_2[randint(0, len(word_parts_2) - 1)] + '\'', 'blue')
                # If it prints a variable
                else:
                    # Append random variable to line of code
                    line_of_code += [colored('x', 'red'), colored('y', 'red'), colored('i', 'red'), createRandomFunctionName()][randint(0, 3)]

                # Close brackets
                line_of_code += ')'
            # If it doesn't have any special function, don't append anything. Just let it be.
            else:
                pass

        # If the operator is an = command:
        else:
            # Append variable to set/change to line of code
            line_of_code += colored(['x', 'y', 'i'][randint(0, 2)], 'red') + ' '
            # Append a variant of '=' to line of code
            line_of_code += ['=', '+=', '-='][randint(0, 2)] + ' '
            # Random to value to set it to / change it by
            random_value = [colored('x', 'red'), colored('y', 'red'), colored('i', 'red'), createRandomFunctionName(), colored(str(randint(-100, 200)), 'magenta'), colored(str((randint(-10000, 20000)) / 100), 'magenta')]
            line_of_code += random_value[randint(0, len(random_value) - 1)]

    # Change indentation

    # Print a space for every indentation at the start of line of code
    line_of_code = ' ' * indentation + line_of_code
    # If it opens a loop, increase indentation by 2
    if line_of_code[-1] == ':':
        indentation += 2

        # Chance to separate it by new line
        if randint(0, 1) == 0:
            print('')

        # Print line of code
        print(line_of_code)

    # If not increasing indentation, there is a chance to decrease it.
    elif indentation > 0 and randint(0, chance_of_closing_loops) == 0:
        # Decrease indentation by 2
        indentation -= 2

        # Print line of code
        print(line_of_code)

        # Chance to separate it by new line
        if randint(0, 7) == 0:
            print('')

        # Chance to decrease it again
        def decreaseIndentationMore(chance):
            # Show that I am referring to the global variable indentation
            global indentation
            # Decrease indentation with a 1/'chance' chance
            if randint(0, chance) == 0 and indentation > 0:
                indentation -= 2
                # Recursion, making big collapses more likely
                decreaseIndentationMore(int(chance / 2))

        # Call the function I just defined
        decreaseIndentationMore(int(chance_of_closing_loops / 2))

    # Else, just print the line
    else:
        print(line_of_code)

    # Wait a small random amount to make it look more human/natural
    sleep(randint(0, 50) / 100)

A sample of what it prints:

print('biglullabies')
i += x
x = x
while False:
    i -= 100
    i += -15.94
    y += 79.43
    print(x)
    y = 163.7

    if x == -91.93:
        x = i
        sleep(2)
        i -= i
        i = lengthOfOurMottoImmediately()

        while True:
            x = -64.49
        y += i

        for y <= -93.07:
            print(i)

            if i > -95.2:

                for i >= 165:
                    x -= 5

                    if x <= -2.27:
                        y = x
                        x -= 43.68
                        i -= y
                        sleep(14)
                    x += i
                i += y
                y = x
                sleep(0.86)
            i += y
        if i > 58.51:
            i -= x
            y = x
            sleep(0.08)
    for i <= 116.02:
        y += 156.83

        for y < -64.24:
            i += createXByTen()
            print('happylullabies')
            i -= 167.4
sleep(0.19)
sleep(0.89)
y = radiusRadiusGradually()
sleep(0.16)


def controlPeacocksImmediately():
    sleep(13)
    i -= i


x += 105
sleep(0.09)
i = x
i = i
x += -41.91
y -= -90.75
print(ifNotchIterative())
while x < x:
    y -= x
    i += y
    x = y
    y = addToCarrotsIterative()


    def radiusCarrotsGradually():

        def turtleYGradually():

            for y <= -31.9:

                def setRadiusByTen():
                    for y < 91.41:
                        y -= y
                        i += i
                        i += y
                        x = x
                        x -= lengthOfNotchByTen()
                        sleep(6)
                        i -= 90.34
                        x = 87.38
                        i = 89
                        print('big lullabies')
                        i = 35.57
                        y = y
                        i = addToRadiusAllOver()

                        while True:
                            print(ifNotchAtLength())
                        sleep(0.91)
                        sleep(0.97)
                        x -= -63
                        i += x

                y += y
                i = 114.08
                print(i)
                y -= lengthOfXIterative()
                sleep(4)
                x = y

                for y < 55:
                    print('big customers')

                    def radiusCarrotsByTen():

                        while x == -10.75:
                            i += i
                            x += y
                            sleep(1)

                    x -= addToPterodactylsImmediately()
            y -= i
            i -= 144.74
            i = addToRadiusByTen()
            i = x
            x += y

            def letVariableByTen():
                x += -31
                sleep(3)
                print(y)
                i += y
                x += 34
                while True:
                    while y in y:
                        sleep(13)
                        x = 113.97
                        i = -99.32
                        i -= setXGradually()

                    print('happy lullabies')

                    if x == y:
                        while False:
                            for i >= 130.93:
                                y += y
                                i -= -61
                                sleep(3)
                            i -= 11.34
                            y = 77.34
                            sleep(14)
                            i = x

                        while i == 84:

                            def changePeacocksByTen():
                                def lengthOfXImmediately():
                                    def letTurtlesGradually():
                                        i = 28
                                        x = letVariableIterative()
                                        if i == x:
                                            y = y
                                            sleep(7)
                                            x -= y
                                            y -= x
                                            sleep(8)
                                            i += turtleRadiusByTen()
                                            print(y)

                                            for i > 157:

                                                def letVariableIterative():
                                                    for y <= 85:
                                                        y = x
                                                        i += x
                                                        i -= lengthOfCarrotsAllOver()

                                                while True:
                                                    y -= 148.92
                                                    i -= i
                                                    print('big customers')

                                                    def radiusTurtlesIterative():
                                                        x = scribbleLengthAllOver()

                                                    def addToNotchGradually():
                                                        i -= x

                                                    while y >= x:
                                                        print(x)
                                                        print(x)
                                                        print(y)
                                                        i -= i
                                                    i = y
                                                    x += 169
                                                    print('biglullabies')
                                                    x += -85.99
x += x


def letRadiusIterative():
    i = 139.48


print('happy customers')
x = y
x -= 128.45
if y <= -46.02:
    y = x
    sleep(0.5)
    x += x
    y -= -22
    if i == x:

        while True:
            y = i
            i -= letPeacocksAllOver()
            while False:
                if i >= 84.1:
                    y = -78
                    x -= changeVariableAllOver()
                    y += i
                y -= createOurMottoRed()
            y = y
            print(y)
            y -= x

If you have any suggestions, please comment them.


r/pythoncoding • • Mar 05 '22

Kakegurui Indian Poker

3 Upvotes

I wrote a Python program based on the Kakegurui Indian Poker game that was aired in episode 4. I feel like, I have successfully completed the game. But if you find any issues or any bug fixes, PR is accepted on Github. Game Tutorial Link: https://animevyuh.org/kakegurui-indian-poker/


r/pythoncoding • • Oct 11 '25

Looking for somebody to run code for me.

0 Upvotes

Let me know if this isn’t allowed Here is the code

Save as commodity_rotator_backtest.py and run with: python commodity_rotator_backtest.py

Requires: pip install yfinance pandas numpy matplotlib

import yfinance as yf import pandas as pd import numpy as np import matplotlib.pyplot as plt from datetime import datetime, timedelta

-------- USER SETTINGS --------

tickers = { "Oil": "USO", "LumberProxy": "WOOD", # timber ETF as lumber proxy "Gold": "GLD", "NatGas": "UNG", "Silver": "SLV" }

start_date = "2024-10-10" end_date = "2025-10-10" start_capital = 10000.0 trade_cost_pct = 0.001 # 0.1% per trade (applied on both sell and buy)

--------------------------------

Helper: download daily close prices

def download_closes(tickers, start_date, end_date): df = yf.download(list(tickers.values()), start=start_date, end=end_date, progress=False, group_by='ticker', auto_adjust=False) # yfinance returns multiindex if multiple tickers; easier to use yf.download(...)[('Close', ticker)] or use yf.download + pivot if isinstance(df.columns, pd.MultiIndex): # build close DataFrame with columns named by friendly key close = pd.DataFrame(index=df.index) for name, tk in tickers.items(): close[name] = df[(tk, "Close")] else: # single ticker case close = pd.DataFrame(df["Close"]).rename(columns={"Close": list(tickers.keys())[0]}) close = close.sort_index() return close

Backtest implementing your rule:

Each trading day (at that day's close): compute that day's point change (close_today - close_prev).

- Find the ETF with largest positive point change (top gainer) and largest negative (bottom loser).

- Sell all holdings of the top gainer (if held) and buy the bottom loser with full capital.

- Execution price = that day's close. Transaction cost = trade_cost_pct per trade side.

def run_rotator(close_df, start_capital, trade_cost_pct): # align and drop days with any missing values (market holidays vary across ETFs) data = close_df.dropna(how='any').copy() if data.empty: raise ValueError("No overlapping trading days found across tickers; try a wider date range or check tickers.") symbols = list(data.columns) dates = data.index

# prepare bookkeeping
cash = start_capital
position = None  # current symbol name or None
shares = 0.0
equity_ts = []
trades = []  # list of dicts

prev_close = None

for idx, today in enumerate(dates):
    price_today = data.loc[today]
    if idx == 0:
        # no prior day to compute change; decide nothing on first row (stay in cash)
        prev_close = price_today
        equity = cash if position is None else shares * price_today[position]
        equity_ts.append({"Date": today, "Equity": equity, "Position": position})
        continue

    # compute point changes: today's close - previous day's close (in points, not percent)
    changes = price_today - prev_close
    # top gainer (max points) and bottom loser (min points)
    top_gainer = changes.idxmax()
    bottom_loser = changes.idxmin()

    # At today's close: execute sells/buys per rule.
    # Implementation choice: always end the day 100% invested in bottom_loser.
    # If currently holding something else, sell it and buy bottom_loser.
    # Apply trade costs on both sides.

    # If we are currently holding the top_gainer, we will necessarily be selling it as part of switching to bottom_loser.
    # Sell current position if not None and either it's different from bottom_loser OR it's the top gainer (explicit rule says sell top gainer).
    # Simpler (and faithful to "always 100% in worst loser"): sell whatever we hold (if any) and then buy bottom_loser (if different).
    if position is not None:
        # sell at today's close
        sell_price = price_today[position]
        proceeds = shares * sell_price
        sell_cost = proceeds * trade_cost_pct
        cash = proceeds - sell_cost
        trades.append({
            "Date": today, "Action": "SELL", "Symbol": position, "Price": float(sell_price),
            "Shares": float(shares), "Proceeds": float(proceeds), "Cost": float(sell_cost), "CashAfter": float(cash)
        })
        position = None
        shares = 0.0

    # now buy bottom_loser with full cash (if we have cash)
    buy_price = price_today[bottom_loser]
    if cash > 0:
        buy_cost = cash * trade_cost_pct
        spendable = cash - buy_cost
        # buy as many shares as possible with spendable
        bought_shares = spendable / buy_price
        # update state
        shares = bought_shares
        position = bottom_loser
        cash = 0.0
        trades.append({
            "Date": today, "Action": "BUY", "Symbol": bottom_loser, "Price": float(buy_price),
            "Shares": float(bought_shares), "Spend": float(spendable), "Cost": float(buy_cost), "CashAfter": float(cash)
        })

    equity = (shares * price_today[position]) if position is not None else cash
    equity_ts.append({"Date": today, "Equity": float(equity), "Position": position})

    # set prev_close for next iteration
    prev_close = price_today

trades_df = pd.DataFrame(trades)
equity_df = pd.DataFrame(equity_ts).set_index("Date")
return trades_df, equity_df

Performance metrics

def metrics_from_equity(equity_df, start_capital): eq = equity_df["Equity"] total_return = (eq.iloc[-1] / start_capital) - 1.0 days = (eq.index[-1] - eq.index[0]).days annualized = (1 + total_return) ** (365.0 / max(days,1)) - 1 # max drawdown cum_max = eq.cummax() drawdown = (eq - cum_max) / cum_max max_dd = drawdown.min() return { "start_equity": float(eq.iloc[0]), "end_equity": float(eq.iloc[-1]), "total_return_pct": float(total_return * 100), "annualized_return_pct": float(annualized * 100), "max_drawdown_pct": float(max_dd * 100), "days": int(days) }

Run everything (download -> backtest -> metrics -> outputs)

if name == "main": print("Downloading close prices...") close = download_closes(tickers, start_date, end_date) print(f"Downloaded {len(close)} rows (daily). Head:\n", close.head())

print("Running rotator backtest...")
trades_df, equity_df = run_rotator(close, start_capital, trade_cost_pct)
print(f"Generated {len(trades_df)} trade records.")

# Save outputs
trades_df.to_csv("rotator_trades.csv", index=False)
equity_df.to_csv("rotator_equity.csv")
print("Saved rotator_trades.csv and rotator_equity.csv")

# Compute metrics
mets = metrics_from_equity(equity_df, start_capital)
print("Backtest Metrics:")
for k, v in mets.items():
    print(f"  {k}: {v}")

# Plot equity curve
plt.figure(figsize=(10,5))
plt.plot(equity_df.index, equity_df["Equity"])
plt.title("Equity Curve — Worst-Loser Rotator (ETF proxies)")
plt.xlabel("Date")
plt.ylabel("Portfolio Value (USD)")
plt.grid(True)
plt.tight_layout()
plt.savefig("equity_curve.png")
print("Saved equity_curve.png")
plt.show()

# Print first & last 10 trades
if not trades_df.empty:
    print("\nFirst 10 trades:")
    print(trades_df.head(10).to_string(index=False))
    print("\nLast 10 trades:")
    print(trades_df.tail(10).to_string(index=False))
else:
    print("No trades recorded.")

r/pythoncoding • • Sep 23 '24

CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Thumbnail reddit.com
0 Upvotes

r/pythoncoding • • Oct 07 '23

ChatGPT 3.5 v. 4 - Comparison - Examples - .docx - Inquiry

0 Upvotes

Comparison between ChatGPT 3.5 and Chat GPT 4 when given the same prompt: "write python script to Mail Merge .docx based on Outlook email contents".

Real world goal/implementation: when a new email in Outlook is received, fetch the data in the body of the email, and then Mail Merge a template based on the input/data fetched from the body of the email.

Examples: see below Code:.

Inquiry: this code needs obvious improvement; but as it was written, how does the code from Chat GPT 3.5 compare to the code from ChatGPT 4?

Code:

# ChatGPT 4 # write python script to Mail Merge .docx based on Outlook email

# contents

import os

from exchangelib import Credentials, Account, DELEGATE

from docx import Document

# 1. Access the Outlook email contents

EMAIL_ADDRESS = '[email protected]'

PASSWORD = 'your_password'

# Set up the credentials and account connection

credentials = Credentials(username=EMAIL_ADDRESS, password=PASSWORD)

account = Account(email_address=EMAIL_ADDRESS, credentials=credentials, autodiscover=True, access_type=DELEGATE)

# Retrieve the most recent unread email

unread_emails = account.inbox.filter(is_read=False)

if unread_emails.count() == 0:

print("No unread emails found!")

exit()

email_content = unread_emails[0].text_body # getting the content of the first unread email

# 2. & 3. Read the .docx template file and replace placeholders

TEMPLATE_PATH = "path_to_your_docx_template.docx"

OUTPUT_PATH = "merged_document.docx"

document = Document(TEMPLATE_PATH)

# Assuming the placeholders are in the format {{placeholder_name}}

# For the sake of this example, we're simply replacing a placeholder with the entire email content.

for paragraph in document.paragraphs:

if '{{placeholder_name}}' in paragraph.text:

paragraph.clear() # clear the existing text

paragraph.add_run(email_content)

# 4. Save the merged .docx document

document.save(OUTPUT_PATH)

print(f"Merged document saved as {OUTPUT_PATH}")

# ChatGPT 3.5 # write python script to Mail Merge .docx based on Outlook email

# contents

import os

import win32com.client

from docx import Document

# Outlook constants

olFolderInbox = 6

olMailItem = 0

# Outlook email subject to filter

email_subject = "Your Filter Subject"

# Word document template file

template_file = "template.docx"

# Output directory for merged documents

output_directory = "merged_documents"

# Create the output directory if it doesn't exist

if not os.path.exists(output_directory):

os.mkdir(output_directory)

# Connect to Outlook

outlook = win32com.client.Dispatch("Outlook.Application")

namespace = outlook.GetNamespace("MAPI")

inbox = namespace.GetDefaultFolder(olFolderInbox)

# Filter emails by subject

filtered_emails = [email for email in inbox.Items if email.Subject == email_subject]

# Load the Word template document

doc = Document(template_file)

# Iterate through filtered emails

for i, email in enumerate(filtered_emails):

# Extract data from the email (customize this part based on your email content)

sender_name = email.SenderName

email_subject = email.Subject

email_body = email.Body

# Replace placeholders in the Word document with email data

for paragraph in doc.paragraphs:

if "{{SenderName}}" in paragraph.text:

paragraph.text = paragraph.text.replace("{{SenderName}}", sender_name)

if "{{EmailSubject}}" in paragraph.text:

paragraph.text = paragraph.text.replace("{{EmailSubject}}", email_subject)

if "{{EmailBody}}" in paragraph.text:

paragraph.text = paragraph.text.replace("{{EmailBody}}", email_body)

# Save the merged document

merged_filename = os.path.join(output_directory, f"merged_document_{i + 1}.docx")

doc.save(merged_filename)

# Close Outlook

outlook.Quit()

print("Mail merge completed.")


r/pythoncoding • • Sep 04 '21

Question .

1 Upvotes

I am trying to make a function that , given two points , returns the list of coordinates that make up the line that intersects them . I've been trying for like 3 weeks and haven't been able to do much yet , any suggestions ?


r/pythoncoding • • Feb 01 '24

Best Python Data Visualization Library to simplify your data in your Python projects

Thumbnail
youtube.com
0 Upvotes

r/pythoncoding • • Oct 05 '22

Phony PyPi package imitates known developer

Thumbnail
snyk.io
4 Upvotes

r/pythoncoding • • Jun 19 '26

Migrate a Python project to a Monorepo (using agents)

2 Upvotes

With Agentic Engineering there's an opportunity to refactor legacy code, but this aspect of AI isn't that that much talked about and seems to be overlooked by teams out there.

I’ve been focusing on this lately, and have added agent skills to the Python Open Source project that I maintain: the Python tools for the Polylith Architecture.

If you don't know about Polylith:
the main use case is having Microservices in a Monorepo, and share code between the services. It’s an Architecture with tooling support. I'm the maintainer of the tooling support for Python that works well with uv, poetry and most of the package & dependency management tools for Python out there. There's more info in the link above, you'll also find the documentation there.

The agent skills that I recently added are for migrating and refactoring an entire Python project into a well-structured, human & agent-friendly Monorepo.

But agents are unpredictable and different models behave differently. I have test-run the skills with Claude Opus and Mistral. If you will try this thing out, please share your feedback how the skills worked for you.

A blog post about this:
https://davidvujic.blogspot.com/2026/06/refactoring-with-ai.html


r/pythoncoding • • Jul 24 '21

OpenAI's New Code Generator: GitHub Copilot (and Codex) | This AI Generates Code From Words

Thumbnail
youtu.be
2 Upvotes

r/pythoncoding • • Mar 27 '24

The weird quirk with rounding in Python

Thumbnail
medium.com
2 Upvotes

r/pythoncoding • • Jan 22 '22

Automatically document Python code using AI

9 Upvotes

https://reddit.com/link/s9w7ws/video/18yv54jwo6d81/player

Out of all the languages I code in, I always found comments to be the most useful within Python projects. I've also never met a single developer who enjoys writing documentation. So, I created a VS Code extension that documents code for you using AI. Let me know what you guys think!


r/pythoncoding • • Sep 05 '21

The Ultimate Face-off: Flask vs. FastAPI

Thumbnail
learn.vonage.com
10 Upvotes

r/pythoncoding • • Sep 27 '21

Whatsapp Bot that Detects Chat Messages and joins your Zoom Meetings

Thumbnail
self.python
3 Upvotes

r/pythoncoding • • Sep 28 '23

2 Problems

3 Upvotes

Hello. I am a newcomer to Python and still learning in class.

So I am supposed to create a program where a user enters a hypothetical student’s name and grade number, and that info is placed in a dictionary, where the student’s name is the key and the grade number is the value. I have a good part of it done, but I have two problems that need to be addressed:

1 - The user needs to enter a valid name. To do this, I need to have it so that the user can only enter letters, hyphens, or apostrophes when the user inputs a student’s name (no numbers or other punctuation marks).

2 - I need to make a grade report where it shows how many students achieved a certain grade in a certain range. For example, 3 students scored 100 and 5 scored 85 —> 3 A’s and 2 B’s.

I am supposed to primarily use loops and functions to achieve this, but not much else (very beginner’s level stuff), but I would still like to hear any help you guys can offer. Thanks in advance.


r/pythoncoding • • Nov 02 '21

I created a boilerplate codebase to deal with crypto scams.

Thumbnail self.cryptocurrency
3 Upvotes