Python3尝试捕获语法更改

时间:2018-02-07 17:05:08

标签: python python-3.x

在python2中,这是有效的:

>>> try:
...     pass
... except Exception as (e, b):
...     pass

但在python3中,我收到语法错误:

>>> try:
...     pass
... except Exception as (e, b):
  File "<stdin>", line 3
    except Exception as (e, b):
                        ^
SyntaxError: invalid syntax

如何在python 3中捕获tuple()异常?

编辑:

经过一些投入,我做了一些挖掘工作,我将改变这个问题:

我在python2中看到了这个语法:

try:
    pass
except Exception, (num, msg):
    pass

我不知道这是做什么的,但语法在python2中是有效的。 这是python3中的语法错误,所以我将其转换为:

try:
    pass
except Exception as (num, msg):
    pass

哪个仍是语法错误。那么,我想现在的问题是,第一种语法的初衷是什么,现在如何在python3中完成?

1 个答案:

答案 0 :(得分:1)

在Python 2中,有效的语法但被捕获的public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler { private static final int REQUEST_CAMERA = 1; final static String serverUrl = ""; private ZXingScannerView scannerView; String res; ImageButton img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); Log.e("OnCreate", "OnCreated"); //ZXingScannerView zxing=(ZXingScannerView)findViewById(R.id.zxscan); scannerView = (ZXingScannerView) findViewById(R.id.zxscan); img=(ImageButton)findViewById(R.id.img1); //scannerView.setResultHandler(this); //scannerView.startCamera(); //zxing.addView(scannerView); //setContentView(scannerView); int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion >= android.os.Build.VERSION_CODES.M) { if (checkPermission()) { Log.e("M", "Permission"); Toast.makeText(getApplicationContext(), "Permission already granted", Toast.LENGTH_LONG).show(); } else { Log.e("R", "Permission"); requestPermission(); } } } private boolean checkPermission() { return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED); } private void requestPermission() { ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA); } public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_CAMERA: if (grantResults.length > 0) { Log.e("Successfull", "Success"); boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (cameraAccepted) { Log.e("accpt", "Accpt"); Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show(); } else { Log.e("ntaccpt", "Not Acpt"); Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (shouldShowRequestPermissionRationale(CAMERA)) { showMessageOKCancel("You need to allow access to both the permissions", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{CAMERA}, REQUEST_CAMERA); } } }); return; } } } } break; } } private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) { new android.support.v7.app.AlertDialog.Builder(MainActivity.this) .setMessage(message) .setPositiveButton("OK", okListener) .setNegativeButton("Cancel", null) .create() .show(); } @Override public void onResume() { super.onResume(); int capi = android.os.Build.VERSION.SDK_INT; if (capi >= android.os.Build.VERSION_CODES.M) { if (checkPermission()) { if (scannerView == null) { scannerView = new ZXingScannerView(this); setContentView(scannerView); } scannerView.setResultHandler(this); scannerView.startCamera(); } else { requestPermission(); } } } @Override public void onDestroy() { super.onDestroy(); scannerView.stopCamera(); scannerView = null; } @Override public void handleResult(final Result result) { res = result.getText(); Log.d("Scanner Result", result.getText()); Log.d("Scanner Result", result.getBarcodeFormat().toString()); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Scan Result"); builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { scannerView.resumeCameraPreview(MainActivity.this); } }); builder.setNeutralButton("Send", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { GetText(); scannerView.resumeCameraPreview(MainActivity.this); } }); builder.setMessage(result.getText()); AlertDialog alert = builder.create(); alert.show(); } public void GetText() //throws UnsupportedEncodingException { String data = res; String text = ""; BufferedReader reader = null; Log.e("Datafirst", data); String requesturi = serverUrl + data; // Send data try { URL url = new URL(requesturi); Log.e("DataSecond", requesturi); if (Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); Log.e("Data Third", data); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; Toast.makeText(MainActivity.this, "Readed Successfully", Toast.LENGTH_SHORT).show(); while ((line = reader.readLine()) != null) { sb.append(line + "\n"); Toast.makeText(MainActivity.this, "Readed Successfully", Toast.LENGTH_SHORT).show(); } text = sb.toString(); } catch (Exception ex) { Log.e("Exceptionio", "Error", ex); ex.printStackTrace(); } finally { try { reader.close(); Log.e("Closed", "Closed"); } catch (Exception ex) { Log.e("Except2", "Error", ex); ex.printStackTrace(); } } Log.e("setText", data); } } 不是元组,因此如果您实际遇到<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <me.dm7.barcodescanner.zxing.ZXingScannerView android:id="@+id/zxscan" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageButton android:id="@+id/img1" android:layout_marginBottom="15dp" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" android:src="@drawable/imgbut" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> ,它仍然会失败:

Exception

所以你想要的只是:

Exception