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

树莓派环境下如何用Java运行带参数的AdafruitDHT.py脚本

Running Adafruit DHT22 Python Script from Java on Raspberry Pi

Hey there! Glad you got your DHT22 sensor up and running with the Python script—let's walk through how to execute that same script with its required parameters directly from Java. There are two reliable approaches to call external processes like Python scripts from Java, and I'll break both down for you:

ProcessBuilder is the more flexible and preferred way to run external commands in Java, as it gives you better control over environment variables, working directories, and input/output streams.

Here's a complete code example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class DHT22JavaRunner {
    public static void main(String[] args) {
        try {
            // Define the command components: python interpreter, script path, sensor type, GPIO pin
            ProcessBuilder processBuilder = new ProcessBuilder(
                "/usr/bin/python3",  // Absolute path to Python 3 (adjust if needed)
                "/home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py",
                "22",
                "4"
            );

            // Optional: Set the working directory to the script's folder (if needed)
            // processBuilder.directory(new File("/home/pi/Adafruit_Python_DHT/examples"));

            // Start the process
            Process process = processBuilder.start();

            // Read the output from the Python script
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream())
            );
            String line;
            System.out.println("Sensor Output:");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // Read any error output (to debug issues)
            BufferedReader errorReader = new BufferedReader(
                new InputStreamReader(process.getErrorStream())
            );
            System.out.println("\nError Output (if any):");
            while ((line = errorReader.readLine()) != null) {
                System.out.println(line);
            }

            // Wait for the process to finish and get exit code
            int exitCode = process.waitFor();
            System.out.println("\nProcess exited with code: " + exitCode);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Key Notes for This Method:

  • Use absolute paths for both the Python interpreter and the script to avoid "file not found" errors (especially if your Java app runs from a different working directory).
  • Always read both the input stream and error stream of the process—if you don't, the process might hang when its output buffer fills up.
  • Adjust the Python path (/usr/bin/python3) if your Raspberry Pi uses a different path (check with which python3 in terminal).

Method 2: Use Runtime.getRuntime().exec()

This is a simpler, more concise approach if you don't need advanced process control. Here's how to use it:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SimpleDHT22Runner {
    public static void main(String[] args) {
        try {
            // Combine the command into a single string (or use a string array)
            String command = "/usr/bin/python3 /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 22 4";
            Process process = Runtime.getRuntime().exec(command);

            // Read output and error streams (same as Method 1)
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            String line;
            System.out.println("Sensor Output:");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            System.out.println("\nError Output (if any):");
            while ((line = errorReader.readLine()) != null) {
                System.out.println(line);
            }

            int exitCode = process.waitFor();
            System.out.println("\nProcess exited with code: " + exitCode);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Important Troubleshooting Tips

  • Permissions: Make sure the user running the Java program has access to the GPIO pins and the script file. You might need to run the Java app with sudo (like sudo java DHT22JavaRunner) if you hit permission errors.
  • Python Dependencies: Ensure the Adafruit_Python_DHT library is available to the Python interpreter being called by Java. If you installed it for the pi user, make sure the Java process runs under the same user or the library is installed system-wide.
  • Path Issues: If you get "python3: command not found", double-check the absolute path to Python using which python3 in the terminal and update it in your Java code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:06:38