This article is the 20th day article of Python Advent Calendar 2020.
I am sorry to be late. I'm sorry.
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.
Unity 2020.2.0a13 IronPython 2.7.11
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.
All you have to do is change .NET to 4.x and you're done.
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.
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());
}
}
It was output safely.
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.
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