![](/img/trans.png)
[英]How to integrate Python scripting in my Android App (like SL4A)
[英]How to integrate python scripting in my python code
我正在編寫 Python 代碼(基於 PyQt5 信號和插槽)。 我需要使我的代碼“可編寫腳本”。 可編寫腳本是指用戶可以自己在用戶定義的 python 腳本中利用內部對象來開發/自動化某些功能,..等。 但我不知道如何清楚地實施它。
我嘗試通過以下方式在 python 中使用(exec)function:
用戶定義.py
def script_entry(main_object_in_my_code):
# Connecting signal from main_object_in_my_code (inherited from QObject) to other functions in this
# file. example:
main_object_in_my_code.event_1.connect(function_1)
@QtCore.pyqtSlot(str)
def function_1 (args):
#do user-defined logic using those args.
然后在我的腳本中,當用戶想要執行它時,他輸入(例如)
源用戶-def.py
主腳本讀取腳本並使用 exec 如下:
with open(script_path) as f:
script = f.read()
exec(script, globals())
問題是觸發了事件,但未執行 function function_1。
我確信這不是正確的方法。 那么,如何使用用戶定義的腳本實現我的代碼(可編寫腳本)?
我建議創建一個 class 並從中擴展,讓“用戶”在需要時調用函數。
如果您沒有與 class inheritance 聯系,請查看本教程
source_def.py
class Main:
def __init__(self):
super(Main, self).__init__()
def script_entry(self, main_object_in_my_code):
main_object_in_my_code.event_1.connect( function_1 )
@QtCore.pyqtSlot(str)
def function_1( self, args ):
#this checks if the function is set
invert_op = getattr(self, "user_function", None)
if callable(user_function):
eval('self.user_function( args )')
用戶定義.py
from source_def import Main
class UserClass( Main ):
def __init__(self):
super(UserClass, self).__init__()
def user_function(self , args ):
print( args )
嘗試這個
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.