I have wrote the following program based on the issue i am facing in my other application,in below program i am calling the python script from nodejs to get some job done ,the python scripts returns some results which is further used in nodejs.
nodeJS :
var pythonShell = require('python-shell');
for(let i=0;i<3;i++){
for(let j=0;j<3;j++){
if(i==j){
var options = {
mode: 'text',
scriptPath: 'python file path',
pythonPath: 'python.exe path',
env : process.env,
args: [i]
};
console.log("====calling Python script for ====",i," ",j);
pythonShell.run('check.py', options, function(err, results){
if(err){
console.log(err);
throw err;
}
else {
console.log("====Python result for ====",i," ",j);
console.log(results[0]);
}
});
}
}
}
check.py
import sys
k = sys.argv[1]
print(k)
limit=10000000
if(k==2):
limit=3
if(k==1):
limit=2
s=0
for i in range(limit):
for j in range(10):
s+=1
print(s," i = ",k)
Output of nodeJs script
====calling Python script for ==== 0 0
====calling Python script for ==== 1 1
====calling Python script for ==== 2 2
====Python result for ==== 2 2
100000000 i = 2
====Python result for ==== 0 0
100000000 i = 0
====Python result for ==== 1 1
100000000 i = 1
Here from the above code you can see that, i am getting the same output even the forloop
is running for less time for i=1 and i=2,Don't know what is going on. Thanks in advance.
edit
: Displaying results with parameters passed in python script
====Python result for ==== 1 1
[ '1\r', '100000000 i = 1\r' ]
====Python result for ==== 0 0
[ '0\r', '100000000 i = 0\r' ]
====Python result for ==== 2 2
[ '2\r', '100000000 i = 2\r' ]
problem here is python script gets passing argument as a string
. So always conditions inside the python script become false
. What you can do is cast string into an integer. Try this in your python code:
import sys
k = int(sys.argv[1])
limit=10000000
if(k==2):
limit=3
if(k==1):
limit=2
s=0
for i in range(limit):
for j in range(10):
s+=1
print(s," i = ",k)
In here you can do
k = int(sys.argv[1])
- cast into an integer
or
if(k=='2'):
limit=3
if(k=='1'):
limit=2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.