-
Notifications
You must be signed in to change notification settings - Fork 0
/
PythonModule.js
96 lines (95 loc) · 4.05 KB
/
PythonModule.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const fs = require('fs')
const exec = require('child_process').exec
const cuid = require('cuid')
const CompilePyModule = (envData, code, cb) => {
if (envData.ext !== 'py')
console.log(`[x]INFO: Provide py ext.`)
else {
const fileName = cuid.slug()
const path = './code/'
fs.writeFile(`${path}${fileName}.py`, code, (err) => {
if (err)
console.log(`[x]ERROR: ${err}`)
else {
var programNotFinished = true
console.log(`[+]INFO: ${fileName}.py is created`)
const command = `python ${path}${fileName}.py`
exec(command, (error, stdout, stderr) => {
if (error) {
console.log(`[+]ERROR: ${fileName}.py contained error while compiling`)
const out = { error: stderr }
cb(out)
}
else {
if (programNotFinished) {
programNotFinished = false
console.log(`[+]INFO: ${fileName}.py successfully executed`)
cb({ out: stdout })
}
}
})
if (envData.options.timeout) {
setTimeout(() => {
if (programNotFinished) {
programNotFinished = false
console.log(`[+]INFO: ${fileName}.py has been terminated`)
var out = { timeout: true }
cb(out)
}
}, envData.options.timeout)
}
}
})
}
}
const CompilePyModuleWithInput = (envData, code, input, cb) => {
if (envData.ext !== 'py')
console.log(`[x]INFO: Provide py ext.`)
else {
const fileName = cuid.slug()
const path = './code/'
fs.writeFile(`${path}${fileName}.py`, code, (err) => {
if (err)
console.log(`[x]INFO: ${err}`)
else {
if (!input)
console.log('[x]INFO: Input is not provided')
else {
fs.writeFile(`${path}${fileName}input.txt`, input, (err) => {
if (err)
console(`[x]ERROR: ${err}`)
else {
var programNotFinished = true
const command = `python ${path}${fileName}.py < ${path}${fileName}input.txt`
exec(command, (error, stdout, stderr) => {
if (error) {
console.log(`[x]ERROR: Error while executing ${fileName}.py`)
const out = { error: stderr }
cb(out)
}
else {
if (programNotFinished) {
programNotFinished = false
console.log(`[+]INFO: ${fileName}.py executed successfully`)
cb({ out: stdout })
}
}
})
if (envData.options.timeout) {
setTimeout(() => {
if (programNotFinished) {
programNotFinished = false
console.log(`[+]INFO: ${fileName}.py has been terminated`)
var out = { timeout: true }
cb(out)
}
}, envData.options.timeout)
}
}
})
}
}
})
}
}
module.exports = { CompilePyModule, CompilePyModuleWithInput }