python - Python 代码可以包含在 NetLogo 代码的主体中吗?
问题描述
正如标题所示,我正在寻找一种将 Python 代码嵌入到 NetLogo 中的方法。到目前为止,我已经找到了NetLogo Python扩展,但据我了解,这个扩展只在下面的 NetLogo 提示符下运行(你放置 Observer/Turtle/etc. 命令的地方),所以更像是一个内置的解释器。
我的问题是,是否有办法使用这个扩展或其他方式将 Python 代码嵌入到 NetLogo 项目的主体中,例如:
; This is an extract of some method/subroutine
print global-peopleNum
(py:run
"print('hello')"
)
set-patch-size 20
; other regular NetLogo code
因此它类似于编译代码而不是解释代码。
解决方案
您可以使用 Python 扩展将 Python 代码直接嵌入到 NetLogo 代码中,它不能仅通过命令中心使用。查看模型库中 NetLogo 附带的Python 基本示例和Python 植绒集群模型。
以下是 Python 基本示例模型中的代码:
extensions [ py ]
to setup ; Here we setup the connection to python and import a few libraries
py:setup py:python
py:run "import math"
py:run "import sys"
py:run "import os"
reset-ticks
end
to go ; make sure everything is ready to go!
py:run "print('go!')"
end
to get-sys-info ; Here we use the `sys` package in python to output some system info
output-print (word "Python directory: " (py:runresult "sys.prefix"))
output-print (word "Platform: " (py:runresult "sys.platform"))
output-print (word "Python copyright: " (py:runresult "sys.copyright"))
output-print ""
end
to gcd ; Use the `math` package's built-in gcd method to calculate the gcd(a,b)
py:set "a" a
py:set "b" b
let result py:runresult "math.gcd(a, b)"
output-print (word "Greatest common divisor of " a " and " b " is: " result)
output-print ""
end
to get-home-directory ; Use the `os` package to get the home directory of the system
let home-dir py:runresult "os.environ['HOME']"
output-print (word "Current home directory is: " home-dir)
output-print ""
end
to join-strings ; join some strings in python
let result joined-strings
output-print (word "Here they are joined: " result)
output-print ""
end
to-report joined-strings ; helper procedure to join strings using a delimiter
py:set "delim" delimiter
py:set "list" read-from-string string-list
report py:runresult "delim.join(list)"
end
to to-upper-case ; upper case some Strings in Python
let result joined-strings
py:set "result" result
set result py:runresult "result.upper()"
output-print (word "Here they are in upper case: " result)
output-print ""
end
推荐阅读
- python - 如何将输入字符串附加到字典键 int 中?
- android - Visual Studio 2015 中的 Xamarin 设计师仅查看黑色
- node.js - 将 JSON 数据从 NodeJS/Express 发送到 EJS 模板时出现问题
- qt - 从属于 Repeater 的 TextField 绑定文本
- excel - How to move shapes along with the cells when sorting by rows in excel
- autotools - 在 `lib_LTLIBRARIES` 中使用配置替换
- c - How to analyze this type of multidimensional array?
- javascript - How can I send data by a form without an input field?
- java - 计算字符串中的大写字母
- unity3d - Unity's IsPointerOverGameObject returning inconsistently