[Unity (C #), Python] Try running Python code in Unity using IronPython

I'm sorry I was late

This article is the 20th day article of Python Advent Calendar 2020.

I am sorry to be late. I'm sorry.

What I wanted to do

I wanted to run the Python code I wrote in the past in Unity.

[Reference link]: [Python] Automatically totals the total number of views of Qiita posted articles using API

I thought it would be convenient to make it an app and pass the input location of personal ID and token via Unity GUI.

** In conclusion, I was able to take a string from Python code and display it on the Unity console. ** **

In the past IronPython used the requests module It seems that it was not straightforward.

[Reference link]: How can I use requests with Ironpython?

Also, there are quite a few articles posted in the past about IronPython, I suffered because there were many changes.

I hope that fewer people will experience the same suffering.

version information

Unity 2020.2.0a13 IronPython 2.7.11

Preparation

There was a god who summarized it in the Package at the link below. Drop it and import it. [Reference link]: Use Python with Unity 3D – the definitive guide

If you don't like it, you can take it from Github and drag and drop it manually. (Since .msi is an installer, it's easy to drop it.)

[Link]: IronLanguages ​​/ ironpython2

I think that it will work if you put everything except exe. Let's create a folder called Plugins in Unity and put it in. IronPythonSet.PNG

All you have to do is change .NET to 4.x and you're done.

IronPythonSettingUnity.PNG

Python side code

This time, I used the following Python code. We have prepared a function that returns a character list. Call this function on the C # side.

qiita.py


# coding: UTF-8
import requests
import json
import math
from msvcrt import getch

class ViewCount():

    USER_ID = 'OKsaiyowa'
    PER_PAGE = 20
    allViews = 0

    headers = {"content-type": "application/json",
            'Authorization': 'Bearer API key'}

    #Send a request and insert a json that includes the total number of posts
    url = 'https://qiita.com/api/v2/users/' + USER_ID
    res = requests.get(url, headers=headers)
    json_qiita_info = res.json()

    #Pull out the number of posts from json
    items_count = json_qiita_info['items_count']

    #Calculate the number of pages
    page = items_count / PER_PAGE

    def count(self):
        
        info_list = list()
        info_list.append('|Article title|Number of views|Like count|')

        #Get all posted articles
        for i in range(int(self.page) + 1):

            #Send a request and insert a json containing the information of each article
            url = 'https://qiita.com/api/v2/authenticated_user/items' + \
                '?page=' + str(i + 1)
            res = requests.get(url, headers=self.headers)
            json_qiita_info = res.json()

            for j in range(self.PER_PAGE):
                try:
                    #Pull ID out of json
                    item_id = json_qiita_info[j]['id']

                    #Send a request and insert a json containing the number of views of the article with the specified ID
                    url = 'https://qiita.com/api/v2/items/' + str(item_id)
                    res = requests.get(url, headers=self.headers)
                    json_view = res.json()

                    #Pull out the number of views from json
                    page_view = json_view['page_views_count']

                    #Addition and substitution to make the total number of views
                    self.allViews += page_view

                    #Display in order of title, number of likes, number of views
                    info_list.append('| ' + json_qiita_info[j]['title'] + ' | ' +
                        str(json_qiita_info[j]['likes_count']) + ' |' +
                        str(page_view) + ' |')

                except IndexError:
                    info_list.append('View total:' + str(self.allViews))
                    #new line
                    info_list = "\n".join(info_list)
                    return info_list
                
        #Output with line break
        info_list = "\n".join(info_list)
        return info_list

#for test
v = ViewCount()
print(v.count())

It's a bit messy, but I'll place this Python file directly under Unity's Asset.

C # side code

Call the function from the Python side code above.

using System.Collections.Generic;
using IronPython.Hosting;
using UnityEngine;

/// <summary>
///Attach to any object on the scene
/// </summary>
public class QiitaViewCountFromPython : MonoBehaviour {
    
    void Start()
    {
        var engine = Python.CreateEngine();

        ICollection<string> searchPaths = engine.GetSearchPaths();
        
        //Add the path of the file to be used
        searchPaths.Add(Application.dataPath);
        searchPaths.Add(Application.dataPath + @"\Plugins\Lib\");
        searchPaths.Add(Application.dataPath + @"\Plugins\Lib\site-packages\");
        engine.SetSearchPaths(searchPaths);

        //Run
        dynamic py = engine.ExecuteFile(Application.dataPath + @"\qiita.py");
        
        //Get class
        dynamic viewCount = py.ViewCount();
        //Display the string returned by the function on the console
        Debug.Log(viewCount.count());
    }
}

result

It was output safely.

PythonUnityQiitaAllView.gif

Task

I didn't make it in time, but I entered the personal ID and token input location. I want to manage to pass it to Python via Unity's GUI.

I will verify it and write more as soon as possible.

Another thing I want to solve is I want to manage the place where it takes almost 2 minutes from execution to output of the result.

It may be unavoidable because I am waiting for a request to be sent back one line at a time. If anyone knows a good way, please let me know.

Reference link

Append, extend, insert to add an element to a list (array) in Python About Python classes Summary of line breaks and convenient operations for Python strings

Recommended Posts

[Unity (C #), Python] Try running Python code in Unity using IronPython
Try using LevelDB in Python (plyvel)
Try using Leap Motion in Python
Try running a function written in Python using Fn Project
Try using the Wunderlist API in Python
Execute Python code on C ++ (using Boost.Python)
Try using the Kraken API in Python
Notes on using code formatter in Python
Try using the BitFlyer Ligntning API in Python
Try using ChatWork API and Qiita API in Python
Try using the DropBox Core API in Python
Next Python in C
Try gRPC in Python
C API in Python 3
Try 9 slices in Python
Try using Tweepy [Python2.7]
Try embedding Python in a C ++ program with pybind11
Perform C # processing after executing Python processing asynchronously in Unity
Extend python in C ++ (Boost.NumPy)
[Python] Try using Tkinter's canvas
Try using Kubernetes Client -Python-
Try LINE Notify in Python
Binary search in Python / C ++
Try running Python with Try Jupyter
Try implementing Yubaba in Python 3
Generate QR code in Python
Character code learned in Python
Wrapper running Hadoop in Python
Translate using googletrans in Python
Using Python mode in Processing
Try running python in a Django environment created with pipenv
Try to make it using GUI and PyQt in Python
Try building a neural network in Python without using a library
Try using Spyder included in Anaconda
Precautions when using pit in Python
[Python] Generate QR code in memory
C code review tool using pycparser
Automatically format Python code in Vim
Try implementing extension method in python
ABC166 in Python A ~ C problem
Try using Pleasant's API (python / FastAPI)
Let's try Fizz Buzz in Python
Try to calculate Trace in Python
Try PLC register access in Python
Using global variables in python functions
Write selenium test code in python
Build and try an OpenCV & Python environment in minutes using Docker
Solve ABC036 A ~ C in Python
Try running the basic information Python sample problem only in the browser
Execute Python code from C # GUI
Try running Jupyter with VS Code
Try to log in to Netflix automatically using python on your PC
Let's see using input in python
How to wrap C in Python
Infinite product in Python (using functools)
Edit videos in Python using MoviePy
Try using Python argparse's action API
Check python code styles using pep8
Try using the Python Cmd module
Solve ABC037 A ~ C in Python
Handwriting recognition using KNN in Python