gpt4 book ai didi

python - Python 代码可以包含在 NetLogo 代码的主体中吗?

转载 作者:行者123 更新时间:2023-12-05 02:45:34 30 4
gpt4 key购买 nike

如标题所示,我正在寻找一种将 Python 代码嵌入到 NetLogo 中的方法。到目前为止,我已经找到了 NetLogo Python扩展,但据我了解,此扩展仅在下面的 NetLogo 提示符下运行(您放置 Observer/Turtle/等命令的位置),因此更像是一个内置解释器。

我的问题是是否有办法,使用这个扩展或其他方式,将 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 代码中,它不能仅通过命令中心使用。查看Python Basic ExamplePython Flocking Clusters模型库中 NetLogo 附带的模型。

这是 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 - Python 代码可以包含在 NetLogo 代码的主体中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65925446/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com