我正在嘗試學習如何在 Node 和 Python 之間交換資料python-shell,在 git repo 上,他們有一些示例代碼:
借用其中的一些代碼,這是app.js:
import {PythonShell} from 'python-shell';
let options = {
mode: 'text',
args: ['get_time()', 'get_weekday()']
};
PythonShell.run('my_script.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
這是my_script.py下面將只列印作業日和當前時間:
from datetime import datetime
# Create datetime object
date = datetime.now()
# Get the weekday value, as an integer
date.weekday()
# Define a list of weekday names
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
def get_weekday():
return days[date.weekday()]
def get_time():
return datetime.now().time()
#print(get_time())
#print(get_weekday())
運行時app.js會拋出錯誤:
(node:15380) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
Uncaught c:\Users\bbartling\Desktop\javascript\stout\test_SO\app.js:1
import {PythonShell} from 'python-shell';
^^^^^^
SyntaxError: Cannot use import statement outside a module
No debugger available, can not send 'variables'
Process exited with code 1
有什么想法可以嘗試嗎?感謝您的任何提示,這里沒有太多智慧。我可以通過在 Python 腳本上呼叫這些函式python-shell嗎?只是想知道我是否可以在這個python-shell包中使用 Javascript從 Python 中檢索當前作業日或當前時間。
uj5u.com熱心網友回復:
替換import {PythonShell} from 'python-shell';為let {PythonShell} = require('python-shell');
編輯:在 .py 檔案中,import sys然后從 nodejs 傳遞的引數將sys.argv作為陣列可用。我想通過放置 if 檢查你可以呼叫特定的函式,最后你在 python 中列印的任何內容都可以results在 js 中使用
樣本:
.py 檔案:
import sys
def log():
print('hello from python')
if sys.argv[1][0]=="1":
log()
.js 檔案:
let { PythonShell } = require("python-shell");
let options = {
mode: "text",
args: "1",
};
PythonShell.run("my_script.py", options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log("results: %j", results);
});
uj5u.com熱心網友回復:
感謝@sandeep.kgp讓我開始這里是一個完整的答案,這要歸功于python-shell的YouTube 視頻的幫助。下面的代碼只是來回傳遞一些值,用 2 個不同的 python 包檢查當前時間。
應用程式.js
let {PythonShell} = require("python-shell");
let options = {
mode: "text",
args: ["datetime","time"],
};
PythonShell.run("my_script.py", options, function (err, results) {
if (err){
console.log(err)
console.log("An error happened")
}else{
// results is an array consisting of messages collected during execution
console.log("results: ", results);
console.log("Python Script Finished");
}
})
my_script.py
import sys, time
from datetime import datetime
date = datetime.now()
today = date.today()
today.strftime("%d/%m/%Y")
def use_datetime():
print("Using datetime package its: ", today)
def use_time():
print("Using the time package its: ", time.ctime())
try:
for arg in sys.argv:
#print(arg)
if arg == "time":
use_time()
elif arg == "datetime":
use_datetime()
else:
print("An arg passed: ", arg)
except Exception as error:
print(f"Error: {str(error)}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395847.html
