Skip to content

Instantly share code, notes, and snippets.

@Rafael09ED
Last active April 11, 2024 03:29
Show Gist options
  • Save Rafael09ED/021f6feee5836eff7b21b0061486649c to your computer and use it in GitHub Desktop.
Save Rafael09ED/021f6feee5836eff7b21b0061486649c to your computer and use it in GitHub Desktop.
Running Typescript code from Python

Running Typescript code from Python

✅ Requires node installation for NPX command
✅ Requires package.json project wrapping typescript code

Pros

  • Typescript
  • Use python for your ipython notebooks
  • Expandable formula to other languages with cli communication
  • Error message passthough

Cons

  • CLI overhead
  • More complex interactions may call for a web server w/ APIs instead
import subprocess
import json
script_name = "typescript_code.ts"
json_data = json.dumps({"key": "value"})
try:
result = subprocess.run(
["npx", "tsx", "getPageMd.ts", json_data],
cwd=os.path.join(os.getcwd(), "../other_directory/cmd_scripts/"),
capture_output=True,
text=True,
check=True,
)
parsed_output = json.loads(result.stdout)
except subprocess.CalledProcessError as e:
print(e.stderr)
exit(2)
print(parsed_output["value"])
import * as process from "process";
type JsonInput = {
input: string,
};
type JsonOutput = {
output: string;
};
const jsonString = process.argv[2];
const inputData = JSON.parse(jsonString) as JsonInput;
const value: string = inputData.input;
(async () => {
const output: JsonOutput = { output: await yourLibrary(value) };
process.stdout.write(JSON.stringify(output));
process.exit();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment