Подавление сообщения об ошибке из подпроцесса.check_output () [duplicate]

вы можете отправить сообщение на другое устройство с помощью этого кода. в этом коде нет необходимости в сервере.

public  String send(String to,  String body) {
            try {

                final String apiKey = "AIzaSyBsY_tfCQjUSWEWuNNwQdC1Vtb0szzz";
                URL url = new URL("https://fcm.googleapis.com/fcm/send");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Authorization", "key=" + apiKey);
                conn.setDoOutput(true);
                JSONObject message = new JSONObject();
                message.put("to", to);
                message.put("priority", "high");

                JSONObject notification = new JSONObject();
               // notification.put("title", title);
                notification.put("body", body);
                message.put("data", notification);
                OutputStream os = conn.getOutputStream();
                os.write(message.toString().getBytes());
                os.flush();
                os.close();

                int responseCode = conn.getResponseCode();
                System.out.println("\nSending 'POST' request to URL : " + url);
                System.out.println("Post parameters : " + message.toString());
                System.out.println("Response Code : " + responseCode);
                System.out.println("Response Code : " + conn.getResponseMessage());

                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // print result
                System.out.println(response.toString());
                return response.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "error";
        }
20
задан lpapp 9 September 2014 в 09:56
поделиться

2 ответа

Чтобы получить как выход процесса, так и возвращаемый код:

from subprocess import Popen, PIPE

p = Popen(["ls", "non existent"], stdout=PIPE)
output = p.communicate()[0]
print(p.returncode)

subprocess.CalledProcessError - это класс. Для доступа к returncode используйте экземпляр исключения:

from subprocess import CalledProcessError, check_output

try:
    output = check_output(["ls", "non existent"])
    returncode = 0
except CalledProcessError as e:
    output = e.output
    returncode = e.returncode

print(returncode)
35
ответ дан jfs 4 September 2018 в 06:58
поделиться

Скорее всего, мой ответ больше не уместен, но я думаю, что он может быть решен с помощью этого кода:

import subprocess
failing_command='ls non_existent_dir'

try:
    subprocess.check_output(failing_command, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    ret =   e.returncode 
    if ret in (1, 2):
        print("the command failed")
    elif ret in (3, 4, 5):
        print("the command failed very much")
2
ответ дан Jonathan 4 September 2018 в 06:58
поделиться
Другие вопросы по тегам:

Похожие вопросы: