You can group all the relevant functions you want to call to class and make a dictionary out of a class that maps to the class function. You can directly call awesome.py without an intermediate index.py. You can extend the class AwesomeFile with your methods
The follow program will take user input -
- which python file to run
- which method to run
- method arguments
- Number of arguments mismatch
- What if unknown methods are given
awesomeFile.py
import sys
class AwesomeFile:
def __init__(self):
pass
def doYourMagic(self):
return self
def anotherThing(self, hoodie, shoe):
print(int(hoodie))
print(int(shoe))
awesomeFile = AwesomeFile()
methods = {m:getattr(awesomeFile, m) for m in dir(AwesomeFile) if not m.startswith('__')}
def run():
method_name = sys.argv[1]
if method_name not in methods:
print(f"Unknown Method {method_name}")
return
methodArgCount = methods[method_name].__code__.co_argcount
if methodArgCount - 1 != len(sys.argv[2:]):
print(f"Method {method_name} takes {methodArgCount - 1} arguments but you have given {len(sys.argv[2:])}")
return
methods[method_name](*sys.argv[2:])
if __name__ == "__main__":
run()
index.js
Note** - You would to install prompt - npm i prompt
'use strict';
var prompt = require('prompt');
const { spawn } = require( 'child_process' );
var prompt_attributes = [
{
name: 'pythonFilePath'
},
{
name: 'cmdLineArgs'
}
];
prompt.start();
prompt.get(prompt_attributes, function (err, result) {
if (err) {
console.log(err);
return 1;
}else {
console.log('Command-line received data:');
var filePath = result.pythonFilePath;
var cmdLineArgs = result.cmdLineArgs;
var args = cmdLineArgs.split(" ");
args.unshift(filePath);
const pythonProgram = spawn( 'python' , args);
pythonProgram.stdout.on( 'data', data => {
console.log( `stdout:\n\n ${data}` );
} );
pythonProgram.stderr.on( 'data', data => {
console.log( `stderr: ${data.data}` );
} );
pythonProgram.on( 'close', code => {
console.log( `child process exited with code ${code}` );
} );
}
});
To run the program -
I/O:
Argument Mistmatch -
prompt: Python File Path. Give absolute or relative path: ../python_files/awesomeFile.py # python file can be any location in the system
prompt: Command Line Arguments. Format = func_name arguments_list (Ex addFunc 1 2): anotherThing 1
Command-line received data:
stdout:
Method anotherThing takes 2 arguments but you have given 1
child process exited with code 0
Function Not found
prompt: Python File Path. Give absolute or relative path: ../python_files/awesomeFile.py
prompt: Command Line Arguments. Format = func_name arguments_list (Ex addFunc 1 2): helloworld 1 2
Command-line received data:
stdout:
Unknown Method helloworld
child process exited with code 0
Success Case:
prompt: Python File Path. Give absolute or relative path: ../python_files/awesomeFile.py
prompt: Command Line Arguments. Format = func_name arguments_list (Ex addFunc 1 2): anotherThing 50 60
Command-line received data:
stdout:
50
60
child process exited with code 0