You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码首次运行执行指定段及树莓派2 GPIO单次响应ON1问题

Hey there! Let's break down your two questions with practical, hands-on solutions:

问题1:如何在Python中实现让指定代码段仅在程序首次运行时执行?

There are a few straightforward ways to handle this, depending on your use case:

  • File marker approach (simple and local)
    Create a tiny marker file that your program checks on startup. If the file doesn't exist, run your one-time code and create the file to skip it next time.

    import os
    
    FIRST_RUN_MARKER = ".initial_run_complete"
    
    if not os.path.exists(FIRST_RUN_MARKER):
        # Your one-time execution code here
        print("Running setup for the first time!")
        # Create the marker to skip this block next launch
        with open(FIRST_RUN_MARKER, "w") as f:
            f.write("1")
    

    Just delete the marker file if you ever need to re-run the initial setup.

  • Config file approach (for state management)
    Use a config file to track whether the first run has completed—ideal if you need to manage multiple app states:

    import configparser
    
    CONFIG_PATH = "app_settings.ini"
    config = configparser.ConfigParser()
    
    # Load existing config or initialize new
    if not config.read(CONFIG_PATH):
        # First run code
        print("Executing initial setup...")
        # Save state to config
        config["APP_STATUS"] = {"first_run_done": "True"}
        with open(CONFIG_PATH, "w") as f:
            config.write(f)
    else:
        # Handle edge case where config existed but state wasn't set
        if config.get("APP_STATUS", "first_run_done", fallback="False") == "False":
            print("Running initial setup now...")
            config["APP_STATUS"]["first_run_done"] = "True"
            with open(CONFIG_PATH, "w") as f:
                config.write(f)
    
  • Environment variable approach (temporary sessions)
    If you only need the one-time code to run per session (resets when the environment restarts):

    import os
    
    if not os.getenv("FIRST_RUN_EXECUTED"):
        print("First run of this session!")
        os.environ["FIRST_RUN_EXECUTED"] = "1"
    
问题2:让树莓派2仅首次收到ON1指令时执行GPIO操作

Looking at your code, we just need to add a simple state tracker to rpi2's script to remember whether we've already run the ON1 GPIO sequence. Here's the modified code:

import select
import GPIO
import time

# Track if we've executed the ON1 GPIO operations before
on1_executed = False

# Assume your socket initialization code (socks, sock1) is here as before

while True:
    ready_socks, _, _ = select.select(socks, [], [])
    for sock in ready_socks:
        data, addr = sock.recvfrom(1024)
        print "recived message:", data
        if 'ON1' in str(data):
            print"empty of water run the pump"
            bytes = "succeeded 1"
            sock1.sendto(bytes, ('192.168.1.27', 6007))
            # Only run GPIO ops if it's the first ON1 received
            if not on1_executed:
                GPIO.output(16, 1)
                time.sleep(0.1)
                GPIO.output(16, 0)
                GPIO.output(18, 1)
                # Mark as executed so we skip this next time
                on1_executed = True
        elif 'OFF1' in str(data):
            print "full of water"
            bytes = "succeeded 2"
            sock1.sendto(bytes, ('192.168.1.27', 6007))
            GPIO.output(18, 0)
            time.sleep(0.1)
            GPIO.output(18, 1)
            GPIO.output(16, 0)
            # Optional: Uncomment below to reset the state when OFF1 is received
            # This lets the GPIO ops run again on the next ON1 after an OFF1
            # on1_executed = False

Quick notes:

  • The on1_executed variable starts as False, so the first ON1 triggers the GPIO actions. After that, it's set to True and those actions are skipped for subsequent ON1 messages.
  • If you want to re-enable the GPIO actions after receiving an OFF1 (e.g., run once every time the state goes from OFF to ON), just uncomment the on1_executed = False line in the OFF1 block.
  • Also, check your rpi1 code: there's a possible typo with so.recvfrom(1024)—I think you meant sock.recvfrom(1024) since you used sock for the send operation.

内容的提问来源于stack exchange,提问作者rabia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:40:36