Android Studio java.io.IOException:无法运行程序"python www.example.com":错误= 13,权限在ProcessBuilder中被拒绝script.py": error=13, Permission denied in ProcessBuilder

lhcgjxsq  于 2023-02-19  发布在  Android
关注(0)|答案(1)|浏览(436)

我正在尝试创建一个Android应用程序,它将是一种购买清单。当我尝试创建一个系统,根据价格标签的照片从列表中删除产品时,问题出现了。我单独编写了一个Python脚本,该脚本可以识别图片中的文本并将其写入文件,但是当我尝试使用ProcessBuilder调用它时,我得到了

java.io.IOException: Cannot run program "python script.py": error=13, Permission denied

我已经尝试了各种各样的命令形式,但是我仍然不能完全理解ProcessBuilder是如何工作的。MainActivity.java:

package com.example.check_list;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.View;
import android.widget.Toast;



import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener{

    private List<String> items_s = new ArrayList<>();
    MyRecyclerViewAdapter adapter;
    SharedPreferences sharedPreferences;
    private static final int CAMERA_REQUEST = 1;
    private final int REQUEST_TAKE_PHOTO = 1;
    private Uri file;
    String mCurrentPhotoPath;
    ThumbnailUtils thumbnail;
    Bitmap help1;
    Context context;
    int TAKE_PHOTO_CODE = 0;
    private final static int TAKE_PICTURE_REQUEST = 1;
    //private ImageView imageView;
    private Uri outputFileUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
        File newdir = new File(dir);
        newdir.mkdirs();

        adapter = new MyRecyclerViewAdapter(this, items_s);
        RecyclerView recycler = findViewById(R.id.recycler);
        recycler.setHasFixedSize(true);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setAdapter(adapter);

        sharedPreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
        Set<String> set = sharedPreferences.getStringSet("items_s", new HashSet<>());
        this.items_s = new ArrayList<>(set);
    }

    @Override
    protected void onStart() {
        super.onStart();

        adapter = new MyRecyclerViewAdapter(this, items_s);
        RecyclerView recycler = findViewById(R.id.recycler);
        recycler.setHasFixedSize(true);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setAdapter(adapter);

        sharedPreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
        Set<String> set = sharedPreferences.getStringSet("items_s", new HashSet<>());
        this.items_s = new ArrayList<>(set);
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        adapter = new MyRecyclerViewAdapter(this, items_s);
        RecyclerView recycler = findViewById(R.id.recycler);
        recycler.setHasFixedSize(true);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setAdapter(adapter);

        sharedPreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
        Set<String> set = sharedPreferences.getStringSet("items_s", new HashSet<>());
        this.items_s = new ArrayList<>(set);
    }

    public void onAddClick(View view) {
        Intent intent = new Intent(MainActivity.this, AddingActivity.class);
        startActivity(intent);
    }

    public void onCameraClick(View view) {
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());

        saveFullImage();
    }

    private void saveFullImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory(),
                "photo.jpg");
        outputFileUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        startActivityForResult(intent, TAKE_PICTURE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TAKE_PICTURE_REQUEST && resultCode == RESULT_OK) {
            ProcessBuilder processBuilder = new ProcessBuilder("$python script.py");
            processBuilder.redirectErrorStream(true);

            Process process = null;
            try {
                process = processBuilder.start();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                int exitCode = process.waitFor();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void onEditClick(View view) {
        Intent editClickIntent = new Intent(MainActivity.this, EditActivity.class);
        editClickIntent.putExtra("items", (Serializable) items_s);
        startActivity(editClickIntent);
    }

    public void onShareClick(View view) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");

        sharedPreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
        Set<String> set = sharedPreferences.getStringSet("items_s", new HashSet<>());
        this.items_s = new ArrayList<>(set);
        String s_items_s = String.join("\n", items_s);

        intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Поделиться");
        intent.putExtra(android.content.Intent.EXTRA_TEXT, s_items_s);

        startActivity(Intent.createChooser(intent, "Share"));
    }

    @Override
    public void onItemClick(View view, int position) {}

    public void onProdClick(View view) {}
}

script.py:

def recognize(path):
    from easyocr import Reader
    reader = Reader(['ru'])
    result = reader.readtext(path, detail = 0)
    
    with open("answer.txt", 'w') as f:
        for i in result:
            f.write(i + "\n")

recognize("photo.jpg")

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.CheckList"
        tools:targetApi="31">

        <activity
            android:name=".EditActivity"
            android:exported="false" />
        <activity
            android:name=".AddingActivity"
            android:exported="false" />
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>

文件script.py位于app/assets文件夹中

xn1cxnb4

xn1cxnb41#

这是运行带参数程序的错误方法:

ProcessBuilder processBuilder = new ProcessBuilder("$python script.py");

必须单独传递参数:

ProcessBuilder processBuilder = new ProcessBuilder("$python", "script.py");

相关问题