导入特定的python模块

时间:2016-05-11 00:34:33

标签: python python-module

假设我有一个文件file1.py,如下所示:

    {
   "status": "ok",
   "count": 2,
   "count_total": 2,
   "pages": 1,
   "posts": [
      {
         "id": 22,
         "type": "userstiago",
         "slug": "rascunho-automatico-2",
         "url": "http://tkdhkd.96.lt/userstiago/rascunho-automatico-2/",
         "status": "publish",
         "title": "Rascunho automático",
         "title_plain": "Rascunho automático",
         "content": "",
         "excerpt": "",
         "date": "2016-05-10 18:00:48",
         "modified": "2016-05-10 18:00:48",
         "categories": [],
         "tags": [],
         "author": {
            "id": 1,
            "slug": "admin",
            "name": "admin",
            "first_name": "Tiago",
            "last_name": "Goes",
            "nickname": "Tiagodread",
            "url": "",
            "description": "Administrador da pagina"
         },
         "comments": [],
         "attachments": [],
         "comment_count": 0,
         "comment_status": "closed",
         "custom_fields": {
            "id": [
               "11111111111111"
            ],
            "name": [
               "Priscila"
            ],
            "pass": [
               "priscila"
            ],
            "client_type": [
               "common"
            ]
         },
         "taxonomy_tipo_cliente": []
      },
      {
         "id": 21,
         "type": "userstiago",
         "slug": "rascunho-automatico",
         "url": "http://tkdhkd.96.lt/userstiago/rascunho-automatico/",
         "status": "publish",
         "title": "Rascunho automático",
         "title_plain": "Rascunho automático",
         "content": "",
         "excerpt": "",
         "date": "2016-05-10 17:41:12",
         "modified": "2016-05-10 17:41:12",
         "categories": [],
         "tags": [],
         "author": {
            "id": 1,
            "slug": "admin",
            "name": "admin",
            "first_name": "Tiago",
            "last_name": "Goes",
            "nickname": "Tiagodread",
            "url": "",
            "description": "Administrador da pagina"
         },
         "comments": [],
         "attachments": [],
         "comment_count": 0,
         "comment_status": "closed",
         "custom_fields": {
            "id": [
               "456589546"
            ],
            "name": [
               "Alfred"
            ],
            "pass": [
               "12345"
            ],
            "client_type": [
               "common"
            ]
         },
         "taxonomy_tipo_cliente": []
      }
   ]
}

我还有另一个文件file2.py为

package tiagogoes.wprestandroidreceiver;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button GetServerData = (Button) findViewById(R.id.GetServerData);

        GetServerData.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                // WebServer Request URL
                String serverURL = "http://tkdhkd.96.lt/api/get_user_posts/";

                // Use AsyncTask execute Method To Prevent ANR Problem
                new LongOperation().execute(serverURL);
            }
        });

    }


    // Class with extends AsyncTask class

    private class LongOperation extends AsyncTask<String, Void, Void> {

        // Required initialization

        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
        String data = "";
        TextView uiUpdate = (TextView) findViewById(R.id.output);
        TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
        int sizeData = 0;
        EditText txtlogin = (EditText) findViewById(R.id.txtlogin);
        EditText txtsenha = (EditText) findViewById(R.id.txtsenha);
        ArrayList<Usuario> users = new ArrayList<>();
        String loginloc, senhaloc;

        protected void onPreExecute() {
            // NOTE: You can call UI Element here.

            //Start Progress Dialog (Message)
            loginloc = txtlogin.getText().toString();
            senhaloc = txtsenha.getText().toString();

            Dialog.setMessage("Please wait..");
            Dialog.show();

            try {
                // Set Request parameter
                data += "&" + URLEncoder.encode("data", "UTF-8") + "=" + txtlogin.getText();

            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {

            /************ Make Post Call To Web Server ***********/
            BufferedReader reader = null;

            // Send data
            try {

                // Defined URL  where to send data
                URL url = new URL(urls[0]);

                // Send POST data request

                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();

                // Get the server response

                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;

                // Read Server Response
                while ((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb.append(line + "");
                }

                // Append Server Response To Content String
                Content = sb.toString();
            } catch (Exception ex) {
                Error = ex.getMessage();
            } finally {
                try {

                    reader.close();
                } catch (Exception ex) {
                }
            }

            /*****************************************************/
            return null;
        }

        protected void onPostExecute(Void unused) {
            // NOTE: You can call UI Element here.

            // Close progress dialog
            Dialog.dismiss();

            if (Error != null) {

                uiUpdate.setText("Output : " + Error);

            } else {

                // Show Response Json On Screen (activity)
                uiUpdate.setText(Content);

                /****************** Start Parse Response JSON Data *************/

                String OutputData = "";
                JSONObject jsonResponse;

                try {

                    /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
                    jsonResponse = new JSONObject(Content);

                    /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
                    /*******  Returns null otherwise.  *******/
                    JSONArray jsonMainNode = jsonResponse.optJSONArray("posts");

                    /*********** Process each JSON Node ************/

                    int lengthJsonArr = jsonMainNode.length();

                    for (int i = 0; i < lengthJsonArr; i++) {
                        /****** Get Object for each JSON node.***********/
                        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                        /******* Fetch node values **********/
                        String id = jsonChildNode.optString("id").toString();
                        String name = jsonChildNode.optString("name").toString();
                        String pass = jsonChildNode.optString("pass").toString();
                        String client_type = jsonChildNode.optString("client_type").toString();


                        Usuario u = new Usuario(id,nome,pass,client_type);

                        users.add(u);


                        for (Usuario us : users) {

                            Log.i("dados WS", us.getNome() + " - " + us.getSenha());

                            if (us.getName().equalsIgnoreCase(loginloc) && us.getPass().equalsIgnoreCase(senhaloc)) {
                                Log.i("Mensagem", "OK");
                            } else {
                                Log.i("Mensagem", "Username or password wrong!");
                            }
                        }


                    }
                    /****************** End Parse Response JSON Data *************/

                    //Show Parsed Output on screen (activity)
                    jsonParsed.setText(OutputData);
                } catch (JSONException e) {

                    e.printStackTrace();
                }


            }
        }

    }

}

如果b中存在语法错误,如果我只导入??

,为什么会抛出错误

2 个答案:

答案 0 :(得分:0)

模块(即:文件)一次性加载,而不是有选择地加载,因为要加载特定的函数/ class / ...,解释器需要解析整个文件,所以语法错误将导致导入失败,如果文件被执行则会发生任何错误。

如果例如在b中你有一个除以零或类似的函数,导致导入失败的原因。

答案 1 :(得分:0)

因为当您导入文件时,编译器会读取正在导入的文件,如果正在导入的文件中有任何错误,编译器将捕获它。 您需要确保您尝试导入的模块中没有错误...