Raspberry Pi chạy tập lệnh python ở chế độ nền

Raspberry Pi là một máy tính bảng đơn tuyệt vời, nhưng giống như hầu hết các máy tính, các chức năng của nó chủ yếu dựa vào đầu vào của con người. Điều đó có nghĩa là bất cứ khi nào bạn khởi động [hoặc khởi động] máy tính của mình, nó sẽ đợi đầu vào của bạn để chạy các chương trình. Điều đó thật tuyệt, nhưng làm cách nào để chương trình của chúng ta tự động chạy mỗi khi máy tính khởi động?

Linux là một hệ điều hành khá phức tạp và do đó, thường có nhiều cách để thực hiện bất kỳ một hành động nào. Để chương trình chạy khi khởi động, chúng tôi sẽ giới thiệu một số cách. Để hiển thị một số chương trình ví dụ, chúng tôi sẽ nhấp nháy đèn LED và biến Raspberry Pi thành đồng hồ

Mặc dù sử dụng Raspberry Pi làm đồng hồ có vẻ như quá mức cần thiết, nhưng thay vào đó, vui lòng thay thế chương trình hoặc tập lệnh của riêng bạn. Bạn cũng có thể sử dụng mã ví dụ làm cơ sở cho trang tổng quan của riêng mình [e. g. hiển thị dự báo địa phương khi bạn thức dậy, thời gian hoạt động của máy chủ cá nhân, số ngày còn lại cho đến khi chương trình yêu thích của bạn, v.v. ] hoặc dự án điện tử

Lưu ý. Hướng dẫn này được viết với phiên bản Raspbian "tháng 6 năm 2018" và Python phiên bản 3. 5. 3. Các phiên bản khác có thể ảnh hưởng đến cách thực hiện một số bước trong hướng dẫn này

Trước khi thêm chương trình của bạn vào bất kỳ tập lệnh khởi động nào, điều cực kỳ quan trọng là bạn phải tự mình kiểm tra chương trình đó trước. Chạy nó chỉ bằng lệnh

language:shell
nano clock.py
2 để đảm bảo không có vấn đề gì với chương trình của bạn. Việc theo dõi các lỗi trong mã của bạn khó hơn nhiều khi nó chạy như một phần của quá trình khởi động

Ba phương pháp được đề cập trong hướng dẫn này là

  • - Có thể là cách dễ nhất và đơn giản nhất để chương trình của bạn chạy khi khởi động. Nhược điểm là các tác vụ bắt đầu bằng rc. cục bộ xảy ra trước khi hệ thống X windows khởi động, điều đó có nghĩa là bạn sẽ không có quyền truy cập vào các thành phần giao diện người dùng đồ họa [GUI]
  • - Được sử dụng để tự động chạy các chương trình của bạn khi LXDE [môi trường màn hình đồ họa được sử dụng bởi Raspbian] bắt đầu. Nó hơi phức tạp hơn rc. cục bộ, nhưng nó cho phép bạn chạy các chương trình yêu cầu các yếu tố đồ họa
  • - Cách mới và phổ biến để tự động khởi động chương trình trong Linux. Nó chắc chắn là phức tạp nhất trong ba, nhưng nó cho phép bạn chạy trước khi LXDE bắt đầu, đợi cho đến khi bạn có quyền truy cập vào các quy trình khác [e. g. mạng, màn hình đồ họa] hoặc đơn giản là khởi động lại chương trình của bạn nhiều lần cho đến khi nó hoạt động. Như vậy, đây là một cách mạnh mẽ để tạo và quản lý các dịch vụ chạy trong nền

Vật liệu cần thiết

Ở mức tối thiểu, bạn sẽ cần một Raspberry Pi, thẻ SD và nguồn điện cho hướng dẫn này. Nếu bạn dự định tạo một bảng điều khiển [hoặc đồng hồ, như được cung cấp bởi mã ví dụ trong phần tiếp theo], bạn sẽ cần một màn hình và bàn phím cho Pi của mình. Nếu bạn muốn thiết lập máy tính để bàn đầy đủ, chúng tôi khuyên bạn nên làm như sau

cách đọc được đề nghị

Nếu bạn không quen thuộc với các khái niệm sau, chúng tôi khuyên bạn nên xem các hướng dẫn này trước khi tiếp tục

Hướng dẫn GUI Python. Giới thiệu về Tkinter

Tkinter là gói giao diện người dùng đồ họa tiêu chuẩn đi kèm với Python. Hướng dẫn này sẽ chỉ cho bạn cách tạo các ứng dụng cửa sổ cơ bản cũng như các ví dụ bảng điều khiển toàn màn hình hoàn chỉnh với các bản cập nhật biểu đồ trực tiếp từ matplotlib

Xin lưu ý. Nếu bạn gặp khó khăn khi xem bất kỳ hình ảnh nào trong hướng dẫn này, vui lòng nhấp vào hình ảnh đó để xem rõ hơn

Mã ví dụ

Trong phần còn lại của hướng dẫn, chúng tôi sẽ hiển thị các chương trình Python khởi động khi khởi động với hai ví dụ. nháy mắt. py và đồng hồ. py. Lưu ý rằng bất kỳ chương trình nào [được biên dịch, tập lệnh, v.v.]. ] có thể được sử dụng, nhưng việc chọn phương pháp phù hợp để bắt đầu tập lệnh của bạn là rất quan trọng. Ví dụ: sử dụng rc. local, mặc dù dễ dàng, nhưng không cấp cho bạn quyền truy cập vào máy chủ X [thứ cung cấp cho bạn màn hình GUI]. So, rc. local cho chương trình GUI không phải là công cụ phù hợp và bạn nên thử một phương pháp khác

Trình tự khởi động Linux là một chuỗi các sự kiện khá phức tạp, có thể dễ dàng trở thành bài viết riêng của nó vào một thời điểm khác. Nếu bạn muốn tìm hiểu thêm về nó, hãy xem các liên kết này

nháy mắt. py

Mặc dù không cần thiết phải kết nối bên ngoài với phần cứng để hiển thị cách chạy chương trình khi khởi động, nhưng đây có thể là một cách hữu ích để cho biết có thứ gì đó đang chạy ẩn, ngay cả khi bạn không nhìn thấy gì trên màn hình. Kết nối đèn LED và điện trở 330 Ω giữa GPIO12 và GND trên Raspberry Pi

Trên Raspberry Pi của bạn, hãy mở một thiết bị đầu cuối và đảm bảo rằng bạn đang ở trong thư mục chính của mình

language:shell
cd /home/pi

Mở một tài liệu mới có tên nháy mắt. py

language:shell
nano blink.py

Copy vào đoạn mã sau

language:python
import time
import RPi.GPIO as GPIO

# Pin definitions
led_pin = 12

# Use "GPIO" pin numbering
GPIO.setmode[GPIO.BCM]

# Set LED pin as output
GPIO.setup[led_pin, GPIO.OUT]

# Blink forever
try:
    while True:
        GPIO.output[led_pin, GPIO.HIGH] # Turn LED on
        time.sleep[1]                   # Delay for 1 second
        GPIO.output[led_pin, GPIO.LOW]  # Turn LED off
        time.sleep[1]                   # Delay for 1 second

# When you press ctrl+c, nicely release GPIO resources
finally:
    GPIO.cleanup[]

Lưu nó bằng ctrl + x, nhấn y khi được yêu cầu lưu và nhấn enter. Chạy chương trình với nội dung sau

language:shell
python blink.py

Bạn sẽ thấy đèn LED bắt đầu nhấp nháy và tắt. Nhấn ctrl + c để dừng chương trình

cái đồng hồ. py

Ví dụ tiếp theo mà chúng ta sẽ sử dụng phức tạp hơn một chút, vì nó dựa trên GUI được tạo bằng gói Tkinter. Chúng tôi sẽ sử dụng chương trình này khi chúng tôi muốn trình bày cách khởi động một chương trình khi khởi động yêu cầu hệ thống cửa sổ X [ví dụ: bạn muốn tạo một bảng điều khiển đồ họa được hiển thị khi khởi động]

Trên Raspberry Pi của bạn [trong thư mục chính của bạn,

language:shell
nano clock.py
3], hãy mở một tài liệu mới có tên clock. py

language:shell
nano clock.py

Copy vào đoạn mã sau

language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]

Lưu nó bằng ctrl + x, nhấn y khi được yêu cầu lưu và nhấn enter. Chạy chương trình với nội dung sau

________số 8

Toàn bộ màn hình của bạn sẽ được chiếm bởi một chiếc đồng hồ khá lớn

Nếu bạn muốn tìm hiểu thêm về cách chương trình này được thực hiện [tôi. e. tạo giao diện người dùng đồ họa của riêng bạn với Tkinter], hãy xem Hướng dẫn GUI Python của chúng tôi. Giới thiệu về Tkinter

Phương pháp 1. rc. địa phương

Chạy chương trình của bạn từ rc. local có thể là phương pháp dễ nhất, nhưng vì rc. local được thực thi trước khi X bắt đầu, bạn sẽ không có quyền truy cập vào các phần tử GUI. Do đó, bạn chỉ nên sử dụng rc. cục bộ để bắt đầu các chương trình không có phần tử đồ họa

Khi hệ điều hành [OS] Linux của bạn khởi động trên Raspberry Pi, nó sẽ trải qua một loạt các mức chạy, xác định trạng thái của hệ thống trong khi khởi động. Bất cứ khi nào mức chạy thay đổi, các tập lệnh điều khiển chạy [rc] khác nhau sẽ được chạy, xử lý việc bắt đầu và dừng các dịch vụ hệ thống khác nhau. Nếu bạn muốn tìm hiểu thêm về tập lệnh rc, hãy xem bài viết này, nhưng với mục đích của chúng tôi, chúng tôi chỉ cần lo lắng về rc. địa phương

các rc. tập lệnh cục bộ được thực thi sau khi tất cả các dịch vụ hệ thống thông thường đã được khởi động [bao gồm cả kết nối mạng, nếu được bật] và ngay trước khi hệ thống chuyển sang cấp chạy nhiều người dùng [theo truyền thống, bạn sẽ nhận được lời nhắc đăng nhập]. Trong khi hầu hết các bản phân phối Linux không cần rc. local, đây thường là cách dễ nhất để chương trình chạy khi khởi động với Raspbian

sửa đổi rc. địa phương

Bạn sẽ cần quyền truy cập cấp gốc để sửa đổi rc. local, hãy làm như vậy với sudo

language:shell
sudo nano /etc/rc.local

Cuộn xuống và ngay trước dòng

language:shell
nano clock.py
4, nhập thông tin sau

language:shell
cd /home/pi
1

Ghi chú. dấu và [&] ở cuối dòng là cần thiết để tập lệnh Python của bạn chạy trong một quy trình khác và không chặn thực thi quy trình khởi động. Không có nó, rc. tập lệnh cục bộ sẽ đợi tập lệnh của bạn kết thúc trước khi tiếp tục và nếu bạn có một vòng lặp vô hạn [như trong nháy mắt của chúng tôi. py], bạn sẽ không bao giờ nhận được lời nhắc đăng nhập

Lưu ý rằng chúng tôi đang gọi tập lệnh của mình với vị trí tệp tuyệt đối [

language:shell
nano clock.py
5], giống như gọi
language:shell
nano clock.py
6 từ bên trong rc. local sẽ khiến python tìm tệp cục bộ [tôi. e. nháy mắt. py nằm trong cùng thư mục với rc. địa phương]. Chúng tôi sử dụng vị trí tệp tuyệt đối để làm cho nó rõ ràng với Python nơi có thể tìm thấy chương trình của chúng tôi

Lưu và thoát bằng ctrl + x, theo sau là y khi được nhắc lưu, rồi nhập

Kiểm tra nó bằng cách khởi động lại Pi của bạn với

language:shell
nano clock.py
7

Xử lý sự cố

Chẳng có gì xảy ra

Nếu tập lệnh của bạn không chạy, hãy đảm bảo rằng tập lệnh của bạn được gọi bằng tên thư mục tuyệt đối [e. g.

language:shell
nano clock.py
8]

Nếu bạn không thể truy cập màn hình nền vì tập lệnh của bạn đang ngăn Linux hoàn tất trình tự khởi động của nó, thì bạn có thể phải lấy một thiết bị đầu cuối nối tiếp. Thực hiện theo để có được một thiết bị đầu cuối nối tiếp vào Pi

Nếu bạn không thể cắm thiết bị đầu cuối nối tiếp vào Raspberry Pi, thì có thể bạn sẽ cần phải cắm thẻ SD của mình vào một máy tính khác [Linux hoặc macOS], điều hướng đến etc/rc. local và xóa dòng gọi tập lệnh Python của bạn

gỡ lỗi

Bạn có thể nhận thấy rằng bạn không thấy bất kỳ lỗi hoặc đầu ra nào từ tập lệnh của mình, vì rc. cục bộ không đăng nhập hoặc xuất bất kỳ thông tin nào. Để có được điều đó, hãy thay đổi lệnh gọi python trong rc của bạn. tập tin cục bộ như sau

language:shell
cd /home/pi
6

Điều này tạo ra một trình bao mới với

language:shell
nano clock.py
9 [đặc quyền siêu người dùng], chạy tập lệnh của bạn và chuyển hướng đầu ra [thiết bị xuất chuẩn] sang trạng thái nhấp nháy. tệp nhật ký.
language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
0 Nói rằng các lỗi [stderr] cũng nên được chuyển hướng đến cùng một tệp nhật ký. Sau khi khởi động lại, bất kỳ đầu ra nào từ tập lệnh Python của bạn [e. g.
language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
1 câu] cũng như các lỗi nên lưu vào nháy. đăng nhập. Để xem nhật ký, hãy nhập thông tin sau vào một thiết bị đầu cuối [lưu ý rằng bạn có thể cần phải dừng chương trình của mình trước để xem nội dung của tệp nhật ký]

language:shell
nano blink.py
0

Sử dụng phiên bản cụ thể của Python

Hóa ra, rc. địa phương chạy trước. bashrc, vì vậy lệnh

language:shell
nano clock.py
2 vẫn đề cập đến Python 2 trong tập lệnh khởi động của chúng tôi. Để gọi Python 3 một cách rõ ràng, chúng ta nên thay đổi rc. lệnh cục bộ để

language:shell
nano blink.py
1

Làm thế nào để dừng chương trình của bạn

Bạn có thể nhận thấy rằng chương trình của mình chạy rất tốt, nhưng không có cách nào dễ dàng để ngăn chặn nó. Phương pháp đơn giản nhất là xóa [hoặc nhận xét] dòng bạn đã thêm vào rc. local sau đó là khởi động lại, nhưng điều đó mất rất nhiều thời gian

Cách nhanh nhất để dừng chương trình của bạn là giết tiến trình Linux của nó. Trong một thiết bị đầu cuối, nhập lệnh sau

language:shell
nano blink.py
2

language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
3 yêu cầu Linux liệt kê tất cả các quy trình hiện tại. Chúng tôi chuyển danh sách đó thành
language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
4, cho phép chúng tôi tìm kiếm từ khóa. Chúng tôi đang tìm kiếm python trong ví dụ này, nhưng vui lòng thay đổi nó thành tên chương trình của bạn hoặc bất kỳ thứ gì bạn đang sử dụng để chạy chương trình của mình. Tìm số ID quy trình [PID] ở bên trái của quy trình được liệt kê và sử dụng lệnh
language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
5 để chấm dứt quy trình đó

language:shell
nano blink.py
3

Đứng lên. Hãy chắc chắn rằng bạn gõ đúng PID. Nếu giết sai quy trình, bạn có thể tạm dừng Linux và cần phải khởi động lại

Nếu bạn đang sử dụng nháy mắt. py, bạn sẽ thấy đèn LED ngừng nhấp nháy

Cách dừng chương trình của bạn chạy khi khởi động

Nếu bạn không muốn chương trình của mình chạy khi khởi động nữa, chỉ cần mở rc. địa phương với

language:shell
sudo nano /etc/rc.local

Xóa dòng mà bạn đã thêm để chạy chương trình của mình, lưu và thoát bằng ctrl + x và y. Khởi động lại máy tính của bạn và chương trình của bạn sẽ không còn chạy sau khi khởi động

Tùy chọn khác

rc. local là một nơi tốt để bắt đầu chương trình của bạn bất cứ khi nào hệ thống khởi động [trước khi người dùng có thể đăng nhập hoặc tương tác với hệ thống]. Nếu bạn muốn chương trình của mình bắt đầu bất cứ khi nào người dùng đăng nhập hoặc mở một thiết bị đầu cuối mới, hãy cân nhắc thêm một dòng tương tự vào

language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
6

Phương pháp 2. tự động bắt đầu

Nếu bạn cần truy cập vào các thành phần từ Hệ thống Cửa sổ X [e. g. bạn đang tạo bảng điều khiển đồ họa hoặc trò chơi], thì bạn sẽ cần đợi máy chủ X khởi tạo xong trước khi chạy mã của mình. Một cách để thực hiện điều này là sử dụng hệ thống

language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
7

Ghi chú. Raspbian dựa trên môi trường máy tính để bàn LXDE. Do đó, vị trí của tập lệnh tự khởi động có thể khác nhau tùy thuộc vào phiên bản phân phối và máy tính Linux cụ thể của bạn

Sau khi môi trường máy tính để bàn của bạn bắt đầu [LXDE-pi, trong trường hợp này], nó sẽ chạy bất kỳ lệnh nào mà nó tìm thấy trong tập lệnh tự khởi động của cấu hình, được đặt tại /home/pi/. config/lxsession/LXDE-pi/autostart cho Raspberry Pi của chúng tôi. Lưu ý rằng thư mục pi có thể khác nếu bạn tạo người dùng mới cho Raspberry Pi của mình. Nếu không tìm thấy tập lệnh tự động khởi động của người dùng, thay vào đó, Linux sẽ chạy tập lệnh /etc/xdg/lxsession/LXDE-pi/autostart toàn cầu

Ngoài việc chạy các lệnh trong chế độ tự động khởi động, Linux cũng sẽ tìm kiếm và thực thi. tập lệnh máy tính để bàn được tìm thấy trong /home/pi/. cấu hình/tự khởi động. Cách dễ nhất để thực thi các chương trình GUI khi khởi động là tạo một trong các chương trình này. tập lệnh máy tính để bàn

Tạo một. tập tin máy tính để bàn

Bạn không cần quyền truy cập cấp cơ sở để sửa đổi tự khởi động và. tập tin máy tính để bàn. Trên thực tế, bạn không nên sử dụng

language:shell
nano clock.py
9, vì bạn có thể ảnh hưởng đến quyền của tệp [e. g. tệp sẽ được sở hữu bởi root] và khiến chúng không thể được thực thi bằng cách tự động khởi động [có quyền ở cấp độ người dùng]

Mở một thiết bị đầu cuối và thực hiện các lệnh sau để tạo thư mục tự khởi động [nếu chưa tồn tại] và chỉnh sửa một. tệp máy tính để bàn cho ví dụ về đồng hồ của chúng tôi

language:shell
nano blink.py
5

Sao chép văn bản sau vào đồng hồ. tập tin máy tính để bàn. Vui lòng thay đổi các biến Tên và Exec cho ứng dụng cụ thể của bạn

language:shell
nano blink.py
6

Ghi chú. Chúng tôi đang gọi python3 một cách rõ ràng ở đây để tránh mọi nhầm lẫn về việc sử dụng phiên bản Python nào

Lưu và thoát bằng ctrl + x, theo sau là y khi được nhắc lưu, rồi nhập. khởi động lại với

language:shell
nano blink.py
7

Khi Raspberry Pi của bạn khởi động, hãy đảm bảo đăng nhập vào máy tính để bàn [nếu nó không tự động làm như vậy]. Tập lệnh của bạn sẽ bắt đầu chạy ngay lập tức

Xử lý sự cố

Chẳng có gì xảy ra

Nếu tập lệnh của bạn không chạy ngay khi bạn nhìn thấy màn hình, có thể có một số vấn đề. Trước tiên, đảm bảo rằng bạn đã đăng nhập [tự động khởi động không bắt đầu cho đến khi bạn đăng nhập]. Bạn cũng có thể thử bật tự động đăng nhập trong

language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
9. Thứ hai, đảm bảo rằng bạn đang sử dụng tên thư mục tuyệt đối [e. g.
language:shell
python clock.py
0]. Thứ ba, hãy thử làm theo một số gợi ý bên dưới để bật thiết bị xuất chuẩn và thiết bị xuất chuẩn để xem điều gì đang xảy ra

Sử dụng phiên bản cụ thể của Python

Hóa ra, autostart chạy trước. bashrc, vì vậy lệnh

language:shell
nano clock.py
2 vẫn đề cập đến Python 2. Để gọi Python 3 một cách rõ ràng, chúng ta nên thay đổi lệnh của mình trong chế độ tự động khởi động thành

language:shell
nano blink.py
8

gỡ lỗi

Thật không may, việc chạy một chương trình từ chế độ tự khởi động gây khó khăn cho việc xuất hoặc đăng nhập vào một tệp và lxterminal [chương trình đầu cuối mặc định trong Raspbian] quá đơn giản để giúp chúng tôi ở đây. Để có được một số loại ghi nhật ký, chúng tôi sẽ cần sử dụng một chương trình đầu cuối khác [chúng tôi sẽ sử dụng xterm]. Mở một thiết bị đầu cuối và nhập lệnh sau

language:shell
nano blink.py
9

trong bạn. desktop, hãy thay đổi lệnh

language:shell
python clock.py
2 của bạn thành lệnh sau

language:python
import time
import RPi.GPIO as GPIO

# Pin definitions
led_pin = 12

# Use "GPIO" pin numbering
GPIO.setmode[GPIO.BCM]

# Set LED pin as output
GPIO.setup[led_pin, GPIO.OUT]

# Blink forever
try:
    while True:
        GPIO.output[led_pin, GPIO.HIGH] # Turn LED on
        time.sleep[1]                   # Delay for 1 second
        GPIO.output[led_pin, GPIO.LOW]  # Turn LED off
        time.sleep[1]                   # Delay for 1 second

# When you press ctrl+c, nicely release GPIO resources
finally:
    GPIO.cleanup[]
0

Khởi động lại Raspberry Pi của bạn. Bây giờ, sau khi bạn đăng nhập vào máy tính để bàn của mình, bạn sẽ thấy một cửa sổ đầu cuối mới mở ra, sau đó chương trình của bạn đang chạy. Nếu bạn dừng chương trình của mình [thoát khỏi chương trình, nhấn ctrl + c trong cửa sổ xterm hoặc tắt quy trình như chi tiết bên dưới], cửa sổ xterm sẽ vẫn mở, cho phép bạn đọc tất cả các thống kê đầu ra và lỗi từ chương trình của mình

Làm thế nào để dừng chương trình của bạn

Nếu chương trình của bạn đang chạy trong nền, có thể không có cách rõ ràng nào để tạm dừng chương trình đó. Bạn luôn có thể xóa. desktop và khởi động lại, nhưng có thể mất một lúc. Một tùy chọn tốt hơn có thể là hủy quy trình được liên kết với chương trình của bạn. Trong một thiết bị đầu cuối, nhập như sau

language:shell
nano blink.py
2

language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
3 yêu cầu Linux liệt kê tất cả các quy trình hiện tại. Chúng tôi gửi kết quả đó tới
language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
4, cho phép chúng tôi tìm kiếm từ khóa. Ở đây, chúng tôi đang tìm kiếm python, nhưng vui lòng thay đổi nó thành tên chương trình của bạn. Tìm số ID quy trình [PID] ở bên trái của quy trình được liệt kê và sử dụng lệnh
language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
5 để chấm dứt quy trình đó

language:shell
nano blink.py
3

Đứng lên. Hãy chắc chắn rằng bạn gõ đúng PID. Nếu giết sai quy trình, bạn có thể tạm dừng Linux và cần phải khởi động lại

Nếu bạn đang sử dụng đồng hồ. py, bạn sẽ thấy ứng dụng thoát ra

Cách dừng chương trình của bạn chạy khi khởi động

Để ngăn chương trình của bạn chạy khi khởi động, bạn chỉ cần xóa. tập tin máy tính để bàn. Trong một thiết bị đầu cuối, nhập lệnh [thay thế đồng hồ. máy tính để bàn với tên cụ thể của bạn. tập tin máy tính để bàn]

language:python
import time
import RPi.GPIO as GPIO

# Pin definitions
led_pin = 12

# Use "GPIO" pin numbering
GPIO.setmode[GPIO.BCM]

# Set LED pin as output
GPIO.setup[led_pin, GPIO.OUT]

# Blink forever
try:
    while True:
        GPIO.output[led_pin, GPIO.HIGH] # Turn LED on
        time.sleep[1]                   # Delay for 1 second
        GPIO.output[led_pin, GPIO.LOW]  # Turn LED off
        time.sleep[1]                   # Delay for 1 second

# When you press ctrl+c, nicely release GPIO resources
finally:
    GPIO.cleanup[]
3

Khởi động lại Pi của bạn và chương trình của bạn sẽ không còn chạy khi khởi động

Phương pháp 3. hệ thống

systemd là phương pháp ưa thích để khởi động ứng dụng khi khởi động, nhưng nó cũng là một trong những phương pháp phức tạp nhất để sử dụng. Với systemd, bạn có thể yêu cầu Linux khởi động một số chương trình nhất định chỉ sau khi một số dịch vụ đã khởi động. Do đó, nó là một công cụ rất mạnh mẽ để khởi tạo các tập lệnh và ứng dụng của bạn

systemd là một bộ công cụ tương đối mới trong thế giới Linux và một trong những mục đích dự định của nó là quản lý các quy trình hệ thống sau khi khởi động. Khi nó được phát hành lần đầu tiên, systemd được dùng để thay thế init. công cụ d để khởi động chương trình. Kể từ năm 2015, hầu hết các bản phân phối chính bao gồm systemd và vì nhiều bản init. d xung quanh để được hỗ trợ kế thừa, bạn có tùy chọn sử dụng một trong hai. Tuy nhiên, hãy lưu ý rằng init. d có thể không được dùng nữa, vì vậy systemd dường như là tương lai [hiện tại]

systemd có thể khá phức tạp và hướng dẫn này chỉ bao gồm những điều cơ bản tuyệt đối để giúp bạn bắt đầu chạy các chương trình của mình khi khởi động. Nếu bạn muốn tìm hiểu sâu hơn về thế giới của systemd, chúng tôi khuyên bạn nên đọc hướng dẫn bắt đầu này

Tạo một tệp đơn vị

Tệp đơn vị là tệp văn bản thuần túy cung cấp thông tin cho systemd về dịch vụ, thiết bị, điểm gắn kết, v.v. Chúng tôi sẽ tạo một tệp đơn vị bắt đầu chương trình của chúng tôi dưới dạng dịch vụ [một quy trình chạy trong nền]. Dưới đây là hai ví dụ về tệp đơn vị. người đầu tiên chạy chớp mắt. py trước khi tải màn hình đồ họa [hữu ích cho môi trường không đầu] và lần thứ hai chạy đồng hồ. py sau khi tải màn hình đồ họa [hữu ích nếu bạn đang tạo bảng điều khiển hoặc GUI]

Tệp đơn vị [Không có GUI]

Nếu chương trình của bạn không yêu cầu GUI [chẳng hạn như chương trình nháy mắt của chúng tôi. py], thì bạn có thể sử dụng mẫu sau để tạo dịch vụ systemd. Nếu bạn cần một GUI [e. g. bạn yêu cầu Hệ thống X Windows đã khởi động], hãy xem phần tiếp theo. Tạo một tệp đơn vị mà không yêu cầu GUI có nghĩa là bạn cũng có thể chạy chương trình của mình khi khởi động trong môi trường không đầu

Tạo một cái mới. tập tin dịch vụ trong thư mục systemd

language:python
import time
import RPi.GPIO as GPIO

# Pin definitions
led_pin = 12

# Use "GPIO" pin numbering
GPIO.setmode[GPIO.BCM]

# Set LED pin as output
GPIO.setup[led_pin, GPIO.OUT]

# Blink forever
try:
    while True:
        GPIO.output[led_pin, GPIO.HIGH] # Turn LED on
        time.sleep[1]                   # Delay for 1 second
        GPIO.output[led_pin, GPIO.LOW]  # Turn LED off
        time.sleep[1]                   # Delay for 1 second

# When you press ctrl+c, nicely release GPIO resources
finally:
    GPIO.cleanup[]
4

Nhập văn bản sau vào tài liệu

language:python
import time
import RPi.GPIO as GPIO

# Pin definitions
led_pin = 12

# Use "GPIO" pin numbering
GPIO.setmode[GPIO.BCM]

# Set LED pin as output
GPIO.setup[led_pin, GPIO.OUT]

# Blink forever
try:
    while True:
        GPIO.output[led_pin, GPIO.HIGH] # Turn LED on
        time.sleep[1]                   # Delay for 1 second
        GPIO.output[led_pin, GPIO.LOW]  # Turn LED off
        time.sleep[1]                   # Delay for 1 second

# When you press ctrl+c, nicely release GPIO resources
finally:
    GPIO.cleanup[]
5

Vui lòng thay đổi

language:shell
python clock.py
6 theo ý muốn. Phím
language:shell
python clock.py
7 biểu thị thời điểm chương trình của chúng ta sẽ chạy. đa người dùng. mục tiêu là trạng thái hệ thống nơi quyền kiểm soát được trao cho người dùng ["hệ vỏ nhiều người dùng"] nhưng trước khi Hệ thống X Windows được khởi động. Điều đó có nghĩa là chương trình của chúng tôi sẽ chạy ngay cả khi không đăng nhập. Bạn có thể thay đổi điều này, tùy thuộc vào dịch vụ nào bạn cần kích hoạt trước khi chạy chương trình của mình [ví dụ:
language:shell
python clock.py
8 nếu bạn cần kết nối mạng]. Xem tại đây để biết danh sách tất cả các mục tiêu

language:shell
python clock.py
9 là lệnh [hoặc tập hợp các lệnh] được sử dụng để bắt đầu chương trình của chúng tôi. Lưu ý rằng chúng tôi đang sử dụng các đường dẫn tuyệt đối đến phiên bản Python mà chúng tôi muốn cũng như vị trí của chương trình của chúng tôi

language:shell
sudo nano /etc/rc.local
0 trong phần
language:shell
sudo nano /etc/rc.local
1 chỉ định mục tiêu mà chúng tôi muốn dịch vụ của mình được đưa vào. Trong ví dụ này, chúng tôi muốn dịch vụ của mình chạy khi nhiều người dùng. đơn vị mục tiêu được chạy [hoặc cụ thể hơn là ngay sau nó, dựa trên tham số
language:shell
python clock.py
7]

Lưu và thoát bằng ctrl + x, theo sau là y khi được nhắc lưu, rồi nhập

Chúng tôi cần nói với systemd để nhận ra dịch vụ của chúng tôi, vì vậy hãy nhập

language:python
import time
import RPi.GPIO as GPIO

# Pin definitions
led_pin = 12

# Use "GPIO" pin numbering
GPIO.setmode[GPIO.BCM]

# Set LED pin as output
GPIO.setup[led_pin, GPIO.OUT]

# Blink forever
try:
    while True:
        GPIO.output[led_pin, GPIO.HIGH] # Turn LED on
        time.sleep[1]                   # Delay for 1 second
        GPIO.output[led_pin, GPIO.LOW]  # Turn LED off
        time.sleep[1]                   # Delay for 1 second

# When you press ctrl+c, nicely release GPIO resources
finally:
    GPIO.cleanup[]
6

Lưu ý rằng bạn sẽ cần nhập lệnh này mỗi khi bạn thay đổi. tệp dịch vụ, vì systemd cần biết nó đã được cập nhật

Sau đó, chúng tôi cần nói với systemd rằng chúng tôi muốn dịch vụ của mình bắt đầu khởi động, vì vậy hãy nhập

language:python
import time
import RPi.GPIO as GPIO

# Pin definitions
led_pin = 12

# Use "GPIO" pin numbering
GPIO.setmode[GPIO.BCM]

# Set LED pin as output
GPIO.setup[led_pin, GPIO.OUT]

# Blink forever
try:
    while True:
        GPIO.output[led_pin, GPIO.HIGH] # Turn LED on
        time.sleep[1]                   # Delay for 1 second
        GPIO.output[led_pin, GPIO.LOW]  # Turn LED off
        time.sleep[1]                   # Delay for 1 second

# When you press ctrl+c, nicely release GPIO resources
finally:
    GPIO.cleanup[]
7

Khởi động lại với

language:shell
nano clock.py
7 để xác minh rằng chương trình của bạn hoạt động. Đèn LED sẽ bắt đầu nhấp nháy sau khi Pi khởi động

Tệp đơn vị [GUI]

Nếu chương trình của bạn yêu cầu các thành phần đồ họa [như trong đồng hồ của chúng tôi. py], thì mẫu sau được khuyến nghị để tạo dịch vụ systemd

Tạo một cái mới. tập tin dịch vụ trong thư mục systemd

language:python
import time
import RPi.GPIO as GPIO

# Pin definitions
led_pin = 12

# Use "GPIO" pin numbering
GPIO.setmode[GPIO.BCM]

# Set LED pin as output
GPIO.setup[led_pin, GPIO.OUT]

# Blink forever
try:
    while True:
        GPIO.output[led_pin, GPIO.HIGH] # Turn LED on
        time.sleep[1]                   # Delay for 1 second
        GPIO.output[led_pin, GPIO.LOW]  # Turn LED off
        time.sleep[1]                   # Delay for 1 second

# When you press ctrl+c, nicely release GPIO resources
finally:
    GPIO.cleanup[]
8

Nhập văn bản sau vào tài liệu

language:python
import time
import RPi.GPIO as GPIO

# Pin definitions
led_pin = 12

# Use "GPIO" pin numbering
GPIO.setmode[GPIO.BCM]

# Set LED pin as output
GPIO.setup[led_pin, GPIO.OUT]

# Blink forever
try:
    while True:
        GPIO.output[led_pin, GPIO.HIGH] # Turn LED on
        time.sleep[1]                   # Delay for 1 second
        GPIO.output[led_pin, GPIO.LOW]  # Turn LED off
        time.sleep[1]                   # Delay for 1 second

# When you press ctrl+c, nicely release GPIO resources
finally:
    GPIO.cleanup[]
9

language:shell
python clock.py
6 có thể là bất kỳ văn bản nào bạn muốn để giúp bạn nhớ dịch vụ này làm gì

Dưới

language:shell
sudo nano /etc/rc.local
5, chúng tôi chỉ định một số biến môi trường. Chúng tôi muốn kết nối với màn hình chính của mình [điều này giả sử chỉ có một màn hình được kết nối với Pi của chúng tôi], vì vậy chúng tôi đặt
language:shell
sudo nano /etc/rc.local
6 thành
language:shell
sudo nano /etc/rc.local
7 và chúng tôi cho ứng dụng của mình biết nơi tìm thông tin xác thực cần thiết để sử dụng hệ thống cửa sổ X với
language:shell
sudo nano /etc/rc.local
8.
language:shell
python clock.py
9 là lệnh chúng tôi muốn chạy [bắt đầu chương trình đồng hồ Python của chúng tôi, trong trường hợp này]

Thật không may với systemd, chúng tôi không thể biết chính xác khi nào hệ thống X sẽ khởi động và chúng tôi không nhất thiết đảm bảo rằng người dùng sẽ đăng nhập [trừ khi bạn đã bật đăng nhập tự động bằng

language:shell
cd /home/pi
10]. Để giải thích cho điều này, chúng tôi sẽ buộc chương trình của chúng tôi khởi động lại [với
language:shell
cd /home/pi
11] cứ sau 10 giây [với
language:shell
cd /home/pi
12] nếu nó không thành công hoặc thoát.
language:shell
cd /home/pi
13 yêu cầu systemd tắt mọi quy trình liên quan đến chương trình của chúng tôi nếu dịch vụ không thành công [hoặc thoát] và
language:shell
cd /home/pi
14 có nghĩa là chúng tôi không bao giờ muốn ngừng cố gắng thực hiện chương trình của mình

Lưu và thoát bằng ctrl + x, theo sau là y khi được nhắc lưu, rồi nhập

Chúng tôi cần nói với systemd để nhận ra dịch vụ của chúng tôi, vì vậy hãy nhập

language:python
import time
import RPi.GPIO as GPIO

# Pin definitions
led_pin = 12

# Use "GPIO" pin numbering
GPIO.setmode[GPIO.BCM]

# Set LED pin as output
GPIO.setup[led_pin, GPIO.OUT]

# Blink forever
try:
    while True:
        GPIO.output[led_pin, GPIO.HIGH] # Turn LED on
        time.sleep[1]                   # Delay for 1 second
        GPIO.output[led_pin, GPIO.LOW]  # Turn LED off
        time.sleep[1]                   # Delay for 1 second

# When you press ctrl+c, nicely release GPIO resources
finally:
    GPIO.cleanup[]
6

Lưu ý rằng bạn sẽ cần nhập lệnh này mỗi khi bạn thay đổi. tệp dịch vụ, vì systemd cần biết nó đã được cập nhật

Sau đó, chúng tôi cần nói với systemd rằng chúng tôi muốn dịch vụ của mình bắt đầu khởi động, vì vậy hãy nhập

language:shell
python blink.py
1

Khởi động lại với

language:shell
nano clock.py
7 để xác minh rằng chương trình của bạn hoạt động. Bạn sẽ thấy chương trình đồng hồ Python của mình chạy sau khi bạn đăng nhập vào màn hình đồ họa của mình

Xử lý sự cố

Chẳng có gì xảy ra

Nếu chương trình của bạn dường như không chạy khi khởi động, một số điều có thể đang xảy ra. Để hiểu rõ hơn về dịch vụ systemd, hãy thử ghi đầu ra vào một tệp hoặc kiểm tra trạng thái của dịch vụ [xem các kỹ thuật khắc phục sự cố bên dưới]

gỡ lỗi

Đầu ra từ systemd [e. g.

language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
1 câu lệnh hoặc thông báo lỗi] được ghi lại bởi hệ thống tạp chí và có thể được xem bằng lệnh sau

language:shell
python blink.py
2

Điều này có thể cung cấp một số thông tin chi tiết về những gì đang diễn ra với dịch vụ hoặc chương trình của bạn

Đăng nhập vào một tập tin

Nếu journalctl không đáp ứng mong đợi của bạn, bạn có thể thử ghi đầu ra vào một tệp. Để làm điều đó, thay đổi cuộc gọi

language:shell
python clock.py
9 như sau [sử dụng đồng hồ. py làm ví dụ]

language:shell
python blink.py
3

Điều này bắt đầu một trình bao bash mới, chạy chương trình của bạn và chuyển hướng đầu ra [thiết bị xuất chuẩn] sang một đồng hồ mới. tệp văn bản nhật ký. Lệnh

language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
0 nói rằng mọi lỗi [stderr] cũng phải được chuyển hướng [ghi vào] cùng một tệp nhật ký. Bất kỳ đầu ra nào [e. g. từ các lệnh
language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
1 của Python] hoặc các lỗi sau đó sẽ được lưu vào đồng hồ. đăng nhập. Bạn có thể xem nhật ký bằng lệnh sau [lưu ý rằng bạn có thể cần dừng dịch vụ và chương trình trước khi xem nhật ký]

language:shell
python blink.py
4

Sử dụng phiên bản cụ thể của Python

Bởi vì tệp đơn vị systemd của bạn có thể sẽ chạy trước. bashrc có thể đặt bí danh lệnh

language:shell
nano clock.py
2 thành Python 3, bạn có thể cần gọi rõ ràng lệnh
language:shell
cd /home/pi
61. Để làm điều đó, chỉ cần đảm bảo rằng lệnh gọi Python của bạn là một vị trí tệp tuyệt đối, ví dụ:
language:shell
cd /home/pi
62

Kiểm tra dịch vụ

Nếu bạn nghi ngờ rằng dịch vụ của mình không chạy, thì bạn có thể muốn kiểm tra trạng thái của nó. Để làm điều đó, hãy nhập lệnh sau

language:shell
python blink.py
5

Điều này sẽ cho bạn biết nếu dịch vụ của bạn đang chạy hoặc nếu có bất kỳ lỗi nào

Bắt đầu và dừng dịch vụ

Đối với một số dịch vụ, như đồng hồ của chúng tôi. ví dụ về dịch vụ, bạn sẽ cần dừng dịch vụ trước khi dừng chương trình. Đó là bởi vì ngay cả khi bạn dừng chương trình [e. g. đồng hồ GUI Python của chúng tôi], dịch vụ sẽ khởi động lại sau 10 giây. Để dừng một dịch vụ, hãy nhập lệnh sau

language:shell
python blink.py
6

Lưu ý rằng việc dừng dịch vụ sẽ gửi lệnh dừng [SIGTERM--tín hiệu kết thúc] tới chương trình của bạn. Trong hầu hết các trường hợp, điều này sẽ dừng dịch vụ và chương trình của bạn. Nếu chương trình của bạn không dừng, hãy xem bên dưới về cách dừng chương trình của bạn

Để bắt đầu một dịch vụ [chẳng hạn như đồng hồ của chúng tôi. ví dụ dịch vụ], bạn có thể nhập lệnh

language:shell
python blink.py
7

Điều này có thể hữu ích để khởi động lại một dịch vụ nếu bạn đã thực hiện các thay đổi đối với dịch vụ đó mà không phải khởi động lại hệ thống. Chỉ cần nhớ chạy

language:shell
cd /home/pi
63 nếu bạn thực hiện bất kỳ thay đổi nào đối với. tập tin dịch vụ

Làm thế nào để dừng chương trình của bạn

Ngay cả khi bạn dừng dịch vụ, chương trình của bạn vẫn có thể chạy ngầm. Cũng giống như trong rc. ví dụ cục bộ và tự động khởi động, chúng tôi sẽ cần tìm số ID quy trình và hủy thủ công. Nhập thông tin sau vào một thiết bị đầu cuối

language:shell
nano blink.py
2

language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
3 yêu cầu Linux liệt kê tất cả các quy trình hiện tại. Chúng tôi gửi kết quả đó tới
language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
4, cho phép chúng tôi tìm kiếm từ khóa "python" [vui lòng thay đổi nó thành tên chương trình của bạn]. Tìm số ID quy trình [PID] ở bên trái của quy trình được liệt kê và sử dụng lệnh
language:python
import tkinter as tk
import tkinter.font as tkFont
import time

###############################################################################
# Parameters and global variables

# Default font size
font_size = -24

# Declare global variables
root = None
dfont = None
frame = None
dtime = None

# Global variable to remember if we are fullscreen or windowed
fullscreen = False

###############################################################################
# Functions

# Toggle fullscreen
def toggle_fullscreen[event=None]:

    global root
    global fullscreen

    # Toggle between fullscreen and windowed modes
    fullscreen = not fullscreen
    root.attributes['-fullscreen', fullscreen]
    resize[]

# Return to windowed mode
def end_fullscreen[event=None]:

    global root
    global fullscreen

    # Turn off fullscreen mode
    fullscreen = False
    root.attributes['-fullscreen', False]
    resize[]

# Automatically resize font size based on window size
def resize[event=None]:

    global time_dfont
    global button_dfont
    global frame

    # Resize font based on frame height [minimum size of 12]
    # Use negative number for "pixels" instead of "points"
    new_size = -max[12, int[[frame.winfo_height[] / 2]]]
    time_dfont.configure[size=new_size]
    new_size = -max[12, int[[frame.winfo_height[] / 30]]]
    button_dfont.configure[size=new_size]


# Read values from the sensors at regular intervals
def update[]:

    global root
    global dtime

    # Get local time
    local_time = time.localtime[]

    # Convert time to 12 hour clock
    hours = local_time.tm_hour
    if hours > 12:
        hours -= 12

    # Add leading 0s
    shours = str[hours]
    smin = str[local_time.tm_min]
    if hours < 10:
        shours = '0' + shours
    if local_time.tm_min < 10:
        smin = '0' + smin

    # Construct string out of time
    dtime.set[shours + ':' + smin]

    # Schedule the poll[] function for another 500 ms from now
    root.after[500, update]

###############################################################################
# Main script

# Create the main window
root = tk.Tk[]
root.title["My Clock"]

# Create the main container
frame = tk.Frame[root, bg='black']

# Lay out the main container [expand to fit window]
frame.pack[fill=tk.BOTH, expand=1]

# Variables for holding temperature and light data
dtime = tk.StringVar[]

# Create dynamic font for text
time_dfont = tkFont.Font[family='Courier New', size=font_size]
button_dfont = tkFont.Font[size=font_size]

# Create widgets
label_time = tk.Label[  frame, 
                        textvariable=dtime, 
                        font=time_dfont, 
                        fg='red', 
                        bg='black']
button_quit = tk.Button[frame, 
                        text="Quit", 
                        font=button_dfont, 
                        command=root.destroy,
                        borderwidth=0,
                        highlightthickness=0, 
                        fg='gray10',
                        bg='black']

# Lay out widgets in a grid in the frame
label_time.grid[row=0, column=0, padx=20, pady=20]
button_quit.grid[row=1, column=0, padx=5, pady=5, sticky=tk.E]

# Make it so that the grid cells expand out to fill window
frame.rowconfigure[0, weight=10]
frame.rowconfigure[1, weight=1]
frame.columnconfigure[0, weight=1]

# Bind F11 to toggle fullscreen and ESC to end fullscreen
root.bind['', toggle_fullscreen]
root.bind['', end_fullscreen]

# Have the resize[] function be called every time the window is resized
root.bind['', resize]

# Schedule the poll[] function to be called periodically
root.after[20, update]

# Start in fullscreen mode and run
toggle_fullscreen[]
root.mainloop[]
5 để chấm dứt quy trình đó

language:shell
nano blink.py
3

Đứng lên. Hãy chắc chắn rằng bạn gõ đúng PID. Nếu giết sai quy trình, bạn có thể tạm dừng Linux và cần phải khởi động lại

Nếu bạn đang sử dụng đồng hồ. py, bạn sẽ thấy ứng dụng thoát ra

Cách dừng chương trình của bạn chạy khi khởi động

Bạn có thể ngăn dịch vụ của mình chạy khi khởi động bằng lệnh sau [thay thế đồng hồ. service với tên tệp dịch vụ cụ thể của bạn]

language:shell
nano clock.py
0

Lưu ý rằng bạn không cần phải xóa. tệp dịch vụ, vì vô hiệu hóa nó sẽ ngăn không cho nó chạy khi khởi động. Tuy nhiên, nếu bạn muốn xóa tệp, bạn có thể sử dụng các lệnh sau [một lần nữa, thay thế clock. service với tên tệp dịch vụ của bạn]

language:shell
nano clock.py
1

Sau đó, khởi động lại hệ thống của bạn để đảm bảo rằng chương trình của bạn không còn chạy khi khởi động nữa

Tài nguyên và Đi xa hơn

Như với hầu hết mọi thứ trên Linux, thường có nhiều cách để hoàn thành một tác vụ. Hướng dẫn này chỉ cho bạn ba phương pháp khác nhau để khởi động chương trình [hoặc tập lệnh] khi khởi động. Cả ba phải được mặc định với Raspbian, có nghĩa là mỗi phương thức sẽ hoạt động với bản cài đặt Raspbian đầy đủ. Nếu bạn sử dụng một hệ điều hành khác [hoặc Raspbian Lite], bạn có thể thấy rằng chỉ một số phương pháp khả dụng, vì vậy hãy chọn phương pháp phù hợp với bạn

Nếu bạn muốn tìm hiểu sâu hơn về từng phương pháp, vui lòng xem tài liệu sau

  • rc. local là một phần của bộ công cụ rc lớn hơn mà bạn có thể sử dụng để lên lịch tác vụ khi khởi động
  • tự động khởi động đi kèm với môi trường máy tính để bàn LXDE trong Raspbian. Các môi trường khác có thể có một công cụ khởi động ứng dụng khác
  • systemd là một bộ công cụ được sử dụng để bắt đầu các tác vụ khác nhau trong Linux

Ngoài ra còn có rất nhiều công cụ Linux khác để giúp bạn bắt đầu một tác vụ khi khởi động. Nếu không có cách nào trong số ba cách trên phù hợp với bạn, chúng tôi khuyên bạn nên kiểm tra

Chủ Đề