base_from_python.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. package services
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/shopspring/decimal"
  7. "hongze/hongze_edb_lib/utils"
  8. "os"
  9. "os/exec"
  10. "reflect"
  11. "strings"
  12. )
  13. func Test() (err error) {
  14. defer func() {
  15. if err != nil {
  16. fmt.Println("err:", err)
  17. }
  18. }()
  19. ///usr/local/bin/python3.9
  20. //exec.Command("bin/bash", "-c")
  21. //cmd := exec.Command("/usr/local/bin/python3.9", "-c", "/Users/roc/go/src/hongze/hongze_edb_lib/test2.py")
  22. //cmd := exec.Command("python3", "-c", "./test2.py")
  23. cmd := exec.Command("python3", "/Users/roc/go/src/hongze/hongze_edb_lib/test2.py")
  24. outputByte, err := cmd.Output()
  25. //fmt.Println(err)
  26. fmt.Println("start")
  27. if err != nil {
  28. return
  29. }
  30. fmt.Println(string(outputByte))
  31. arr := strings.Split(string(outputByte), "result=")
  32. arrLen := len(arr)
  33. //fmt.Println(arr)
  34. if arrLen <= 1 {
  35. err = fmt.Errorf("python运算结果异常")
  36. return
  37. }
  38. resultStr := arr[arrLen-1]
  39. fmt.Println(resultStr)
  40. var dataMap map[string]float64
  41. json.Unmarshal([]byte(resultStr), &dataMap)
  42. fmt.Println(dataMap)
  43. //i, err := python3.Py_Main(os.Args)
  44. //if err != nil {
  45. // fmt.Printf("error launching the python interpreter: %s\n", err)
  46. // os.Exit(1)
  47. //}
  48. ////commStr := "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport pymysql\nimport pandas as pd\nfrom test_bak import sql_config\n\ndb = pymysql.connect(**sql_config)\ndb.autocommit(1)\ncursor = db.cursor()\npandas_fetch_all = pd.read_sql\n\n# 返回数据\nresult = {}\n\n# 格式化返回数据\ndef format_data(data: pd.DataFrame,\n index_str: str = \"data_time\",\n value_str: str = \"value\"\n ) -> dict:\n \"\"\"\n Parameters\n ----------\n data : pandas的DataFrame数据结构.\n index_str : 对象下标字符串,在pandas的DataFrame中的列名.\n value_str : 对象值字符串,在pandas的DataFrame中的列名\n\n Returns\n -------\n DataFrame or Iterator[DataFrame]\n 例子:{'2007-01-09': 3220.0, '2007-01-10': 3230.0}\n\n \"\"\"\n tmp_result = {}\n for num in range(1, data.index.size): # 迭代 所有的指标\n tmp_result[data[index_str][num]] = data[value_str][num]\n return tmp_result\n\n\ndef query():\n edb_code = 's0033227'\n data_time = '2002-03-17'\n # field_name = '平均温度'\n sql1 = f\"\"\"SELECT data_time,`value` FROM edb_data_wind WHERE edb_code = '{edb_code}' and data_time > '{data_time}' ;\"\"\"\n raw = pandas_fetch_all(sql1, db)\n raw['data_time_str'] = raw['data_time'].apply(lambda x: x.strftime(\"%Y-%m-%d\"))\n format_result = format_data(raw, \"data_time_str\", \"value\")\n print(format_result)\n return format_result\n\n\nresult = query()\ndb.close()\n"
  49. ////i := python3.PyRun_SimpleString(commStr)
  50. //fmt.Println(i)
  51. return
  52. }
  53. // EdbDataFromPython 通过python代码获取到的指标数据
  54. type EdbDataFromPython struct {
  55. Date map[int]string `json:"date"`
  56. Value map[int]float64 `json:"value"`
  57. }
  58. // EdbDataStrFromPython 通过python代码获取到的指标数据(interface数据)
  59. type EdbDataStrFromPython struct {
  60. Date map[int]string `json:"date"`
  61. Value map[int]interface{} `json:"value"`
  62. }
  63. // ExecPythonCode 执行Python代码
  64. func ExecPythonCode(edbCode, reqCode string) (dataMap EdbDataFromPython, err error, errMsg string) {
  65. defer func() {
  66. if err != nil {
  67. fmt.Println("err:", err)
  68. }
  69. }()
  70. //获取python文件的绝对地址
  71. pythonFile, err := getPythonFileAbsolutePath(edbCode)
  72. if err != nil {
  73. return
  74. }
  75. pthonCodeStr := getPythonFrontStr() + reqCode + getPythonLaterStr()
  76. fileHandle, err := os.OpenFile(pythonFile, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0766)
  77. if err != nil {
  78. return
  79. }
  80. defer func() {
  81. os.Remove(pythonFile)
  82. }()
  83. _, err = fileHandle.Write([]byte(pthonCodeStr))
  84. if err != nil {
  85. return
  86. }
  87. fileHandle.Close()
  88. cmd := exec.Command(utils.PYTHON_PATH, pythonFile)
  89. var out, errMsgOut bytes.Buffer
  90. cmd.Stdout = &out
  91. cmd.Stderr = &errMsgOut
  92. err = cmd.Start()
  93. if err != nil {
  94. errMsg = errMsgOut.String()
  95. }
  96. err = cmd.Wait()
  97. if err != nil {
  98. errMsg = errMsgOut.String()
  99. return
  100. }
  101. outputByte := out.String()
  102. if err != nil {
  103. return
  104. }
  105. //fmt.Println(string(outputByte))
  106. arr := strings.Split(string(outputByte), "result=")
  107. arrLen := len(arr)
  108. //fmt.Println(arr)
  109. if arrLen <= 1 {
  110. err = fmt.Errorf("python运算结果异常")
  111. return
  112. }
  113. resultStr := arr[arrLen-1]
  114. //fmt.Println(resultStr)
  115. var dataMapStr EdbDataStrFromPython
  116. //先将value转为interface
  117. err = json.Unmarshal([]byte(resultStr), &dataMapStr)
  118. if err != nil {
  119. return
  120. }
  121. dataMap.Date = make(map[int]string)
  122. dataMap.Value = make(map[int]float64)
  123. //将value为nil的给过滤掉
  124. i := 0
  125. lenData := len(dataMapStr.Date)
  126. for k := 1; k < lenData; k++ {
  127. date := dataMapStr.Date[k]
  128. tmpValue := dataMapStr.Value[k]
  129. if reflect.TypeOf(tmpValue) != nil {
  130. if reflect.TypeOf(tmpValue).Kind() == reflect.Float64 {
  131. dataMap.Date[i] = date
  132. dataMap.Value[i], _ = decimal.NewFromFloat(reflect.ValueOf(tmpValue).Float()).Truncate(4).Float64() //保留4位小数
  133. i++
  134. }
  135. }
  136. }
  137. //err = json.Unmarshal([]byte(resultStr), &dataMap)
  138. //fmt.Println(dataMap)
  139. return
  140. }
  141. // getPythonFileAbsolutePath 获取python文件的绝对地址
  142. func getPythonFileAbsolutePath(edbCode string) (pythonFile string, err error) {
  143. uploadDir := utils.STATIC_DIR + "python/"
  144. err = os.MkdirAll(uploadDir, 0766)
  145. if err != nil {
  146. return
  147. }
  148. pythonFile = uploadDir + fmt.Sprint(edbCode, "_", utils.GetRandDigit(16), ".py")
  149. if utils.RunMode != "release" {
  150. dir, tmpErr := os.Getwd()
  151. if tmpErr != nil {
  152. err = tmpErr
  153. return
  154. }
  155. pythonFile = dir + "/" + pythonFile
  156. }
  157. return
  158. }
  159. // getPythonFrontStr 获取python前面的代码
  160. func getPythonFrontStr() string {
  161. //return "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport json\n\nimport pymysql\nimport pandas as pd\n\nsql_config = {\n 'host': 'rm-uf67kg347rhjfep5c1o.mysql.rds.aliyuncs.com',\n 'port': 3306,#主机号\n 'user': 'hz_technology',#账户名\n 'passwd': 'hongze@2021',#密码\n 'db': 'test_hz_data',\n 'charset': 'utf8mb4',\n 'cursorclass': pymysql.cursors.DictCursor\n}\n\ndb = pymysql.connect(**sql_config)\ndb.autocommit(1)\ncursor = db.cursor()\npandas_fetch_all = pd.read_sql\n\n# 返回数据\nresult = {}\n\n# 格式化返回数据\ndef format_data(data: pd.DataFrame,\n index_str: str = \"data_time\",\n value_str: str = \"value\"\n ) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n data : pandas的DataFrame数据结构.\n index_str : 对象下标字符串,在pandas的DataFrame中的列名.\n value_str : 对象值字符串,在pandas的DataFrame中的列名\n\n Returns\n -------\n DataFrame or Iterator[DataFrame]\n 例子:{'2007-01-09': 3220.0, '2007-01-10': 3230.0}\n\n \"\"\"\n index_list = [] # 空列表\n value_list = [] # 空列表\n\n for num in range(1, data.index.size): # 迭代 所有的指标\n index_list.append(data[index_str][num])\n value_list.append(data[value_str][num])\n\n tmp_data = {\n \"date\": index_list,\n \"value\": value_list\n }\n pd_data = pd.DataFrame(tmp_data)\n # print(pd_data)\n return pd_data\n"
  162. str := fmt.Sprintf("#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport json\n\nimport pymysql\nimport pandas as pd\n\nsql_config = {\n 'host': '%s',\n 'port': 3306,#主机号\n 'user': '%s',#账户名\n 'passwd': '%s',#密码\n 'db': '%s',\n 'charset': 'utf8mb4',\n 'cursorclass': pymysql.cursors.DictCursor\n}\n\ndb = pymysql.connect(**sql_config)\ndb.autocommit(1)\ncursor = db.cursor()\npandas_fetch_all = pd.read_sql\n\n# 返回数据\nresult = {}\n\n# 格式化返回数据\ndef format_data(data: pd.DataFrame,\n index_str: str = \"data_time\",\n value_str: str = \"value\"\n ) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n data : pandas的DataFrame数据结构.\n index_str : 对象下标字符串,在pandas的DataFrame中的列名.\n value_str : 对象值字符串,在pandas的DataFrame中的列名\n\n Returns\n -------\n DataFrame or Iterator[DataFrame]\n 例子:{'2007-01-09': 3220.0, '2007-01-10': 3230.0}\n\n \"\"\"\n index_list = [] # 空列表\n value_list = [] # 空列表\n\n for num in range(1, data.index.size): # 迭代 所有的指标\n index_list.append(data[index_str][num])\n value_list.append(data[value_str][num])\n\n tmp_data = {\n \"date\": index_list,\n \"value\": value_list\n }\n pd_data = pd.DataFrame(tmp_data)\n # print(pd_data)\n return pd_data\n\n", utils.PYTHON_MYSQL_HOST, utils.PYTHON_MYSQL_USER, utils.PYTHON_MYSQL_PASSWD, utils.PYTHON_MYSQL_DB)
  163. return str
  164. }
  165. // getPythonFrontStr 获取python结尾的代码
  166. func getPythonLaterStr() string {
  167. return "\n\nprint(\"result=\", result.to_json())\ndb.close()"
  168. }