iT邦幫忙

0

javascript 如何取得python執行結果後的值

bojing 2019-12-13 09:10:1712161 瀏覽

請教各位大大,需求是javascript執行本地client端電腦的python檔,把執行後的值顯示在網頁的textbox裡面,我卡在怎麼把執行後的值顯示在網頁的 textbox裡面或者是 段落裡,附上我的程式碼與執行結果。

html:

script type="text/javascript"
var cc="C:/Python25/test.py";
    function start(strPath){

        var   objShell   =   new   ActiveXObject("wscript.shell");
       objShell.Run(strPath) ;
       
        //objShell   =   null;
    	
  }

       var y=document.getElementById("demo");
    	y.innerHTML=start(cc);
script

body:

body
請輸入要執行的程式路徑:
p id="demo"> /p
input type="button" value="SHOW" onclick=""
body

python:

-- coding: utf-8 --

print('HI')

#import serial
#import sys
#ser = serial.Serial('COM1', 9600, timeout=0.5)
#ser.read(1) # 小括號內可以填入一次要讀取的byte數

#data=ser.readline() # 讀取一列資料直到換行符號

#print data
#ser.close()

python執行結果:
https://ithelp.ithome.com.tw/upload/images/20191213/201169168PNgmzfg5V.png

網頁執行結果:
https://ithelp.ithome.com.tw/upload/images/20191213/20116916ORlaU1IJBX.pnghttps://ithelp.ithome.com.tw/upload/images/20191213/20116916VOODzoClwp.png

以上

ccutmis iT邦高手 2 級 ‧ 2019-12-13 09:42:39 檢舉
解法很多的啦,比如 :
Google 搜 'python selenium 教學'
https://freelancerlife.info/zh/blog/python%E7%B6%B2%E8%B7%AF%E7%88%AC%E8%9F%B2%E6%95%99%E5%AD%B8-selenium%E5%9F%BA%E6%9C%AC%E6%93%8D%E4%BD%9C/
或者 PYAUTOGUI 土炮作法 你需要的是OPEN YOUR MIND AND GOOGLE
froce iT邦大師 1 級 ‧ 2019-12-13 10:35:57 檢舉
ㄜ,他的問題是根本不知道怎麼接框架...
ccutmis iT邦高手 2 級 ‧ 2019-12-13 11:09:48 檢舉
o_o"
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
3
dragonH
iT邦超人 5 級 ‧ 2019-12-13 09:29:55

直接從 browser 執行呼叫可能沒辦法

可能啦

如果透過後端呼叫

就很簡單

後端用 nodejs 的話

可以用 child_process 呼叫

bojing iT邦新手 5 級 ‧ 2019-12-13 16:27:07 檢舉

var exec = require("child_process").exec;

exec('test.py',function(error,stdout,stderr){
if(stdout.length >1){
return console.log(stdout);
} else {
console.log("you don\’t offer args");
}
if(error) {
console.info('stderr :', stderr);
}
});

我cmd 下node這段可以顯示出HI
但用瀏覽器執行這段還是無法
顯示 Uncaught ReferenceError: require is not defined
at test.js:1
我查了一下,瀏覽器不支援require()......

https://ithelp.ithome.com.tw/upload/images/20191213/20116916dXbvoLBXZE.png

dragonH iT邦超人 5 級 ‧ 2019-12-13 17:10:50 檢舉

啊我就說後端了阿XD

3
froce
iT邦大師 1 級 ‧ 2019-12-13 10:49:52

簡單的說,你想要的是 https://webduino.io/ ,只是你要python版的。

目前python好像沒有整合得那麼好的套件。不過要做也很簡單。
用flask做伺服器,按鈕後執行你要的功能,然後傳回去就行。
不過要做到漂亮像是連續介接資料到網頁畫圖,這就要很多其他的知識了。

下面的是用你的code拼出來的虛擬碼,不會動我不負責,因為你本來的code看起來就不會動了。

from flask import Flask, escape, request

app = Flask(__name__)

html = """
<script type="text/javascript">
.....  #你的前端JS不可能直接執行python
<script>

<body>
 {}
<body>
"""

def clickAction():
    ser = serial.Serial('COM1', 9600, timeout=0.5)
    ser.read(1) # 小括號內可以填入一次要讀取的byte數
    data=ser.readline() # 讀取一列資料直到換行符號
    print(data)
    ser.close()
    return data

@app.route('/')
def hello():
    data = clickAction()
    return html.format(str(data))
bojing iT邦新手 5 級 ‧ 2019-12-13 16:50:27 檢舉

如果是要IIS伺服器有辦法運行嗎?
其實我主要是要抓磅秤秤重值給網頁的textbox,再存到資料庫

froce iT邦大師 1 級 ‧ 2019-12-13 17:03:02 檢舉

要在windows下,你可以用 waitress 來當wsgi server,然後用iis的url redirect module來當reverse proxy。

不過我覺得你還是好好發包給別人寫吧,看到你的code覺得你離完成還很遠。

2
ccutmis
iT邦高手 2 級 ‧ 2019-12-13 14:40:56

分享一個土炮作法:
用HTA呼叫dos指令來執行python(cmd例 "Python D:\test.py")
以下是執行過程


(1)在桌面上建立一個文字檔,並將它命名為"SILLY.HTA",然後以notepad++(或其它純文字編輯軟體,勿使用記事本)開啟,貼入下列源碼並存檔關閉。

<HTA:APPLICATION>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" />
<title>My Silly Application</title>
<style>
*,html,body{margin:0;padding:0;box-sizing:border-box;}
h3{font-size:1.6em;padding:20px 0x;text-align:center;background:#666;color:#FFF;height:90px;}
.controls{height:50px;padding:20px 0px;text-align:center;font-size:1.2em;}
.controls input,.controls button{font-size:1.2em;height:1.5em;}
textarea{font-size:1.5em;width:100%;height:150px;border:solid 5px #666;}
</style>
</head>
<body>
<div><h3>用HTA(javascript) 呼叫DOS命令執行.py </h3></div>
<div class="controls">
<label for="py_path">Python檔案路徑</label><input type="file" id="py_path" value="" />
<button onclick="execPy()">RUN</button>
</div>
<textarea accesskey="k"></textarea>
<script language="javascript">
window.resizeTo(640, 380);
function execPy(){
  var py_path=document.getElementById('py_path').value;
  if(py_path.search(".py")!==-1){
    shell = new ActiveXObject ("Shell.Application");
    x='Python '+py_path;
    shell.ShellExecute("cmd.exe", "/k " + x, "", "open", 1);
  }else{
    alert('尚未選取文件 或 選取的文件不是python檔!\n\n請重新選取...');
  }
}
</script>
</body>
</html>
</HTA>

(2)在桌面建立一個文字檔並命名為 "silly_test.py" 以notepad++(或其它純文字編輯軟體,勿使用記事本)開啟,貼入下列源碼並存檔關閉。

import win32gui
import re,os
import pyautogui

class WindowMgr:
    """Encapsulates some calls to the winapi for window management"""

    def __init__ (self):
        """Constructor"""
        self._handle = None

    def find_window(self, class_name, window_name=None):
        """find a window by its class_name"""
        self._handle = win32gui.FindWindow(class_name, window_name)

    def _window_enum_callback(self, hwnd, wildcard):
        """Pass to win32gui.EnumWindows() to check all the opened windows"""
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) is not None:
            self._handle = hwnd

    def find_window_wildcard(self, wildcard):
        """find a window whose title matches the wildcard regex"""
        self._handle = None
        win32gui.EnumWindows(self._window_enum_callback, wildcard)

    def set_foreground(self):
        """put the window in the foreground"""
        win32gui.SetForegroundWindow(self._handle)

output_str="Hello World!"
print(output_str)

w = WindowMgr()
#找到標題文字包含Silly的視窗,將它設為作用中視窗
w.find_window_wildcard(".*Silly*")
w.set_foreground()
pyautogui.keyDown('alt')
pyautogui.press('k')
pyautogui.keyUp('alt')
pyautogui.typewrite(output_str, interval=0.25) 
#要讓 pyautogui輸入中文 請看這篇
#https://blog.csdn.net/ibiao/article/details/77859997
exit()

註: 請先確認 Python版本為3.7(或更新版本)
並已安裝 pywin32 與 PyAutoGUI 模組
(pip install pywin32)(pip install PyAutoGUI)
最好先在cmd模式底下確定silly_test.py能正常執行,就可以用HTA呼叫它測試了~

這裡我把範例上傳到網路上提供您參考。
http://www.web3d.url.tw/ITHELP/tmp/SILLY_HTA_RUN_PY.zip

當然最好還是用樓上邦友們建議的方式,我用的這個是非常古早的土炮方法,可當作考古題來看。

我要發表回答

立即登入回答