Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ export class PythonShell extends EventEmitter {
static runString(code: string, options?: Options) {
// put code in temp file
const randomInt = getRandomInt();
const filePath = tmpdir + sep + `pythonShellFile${randomInt}.py`;
const filePath = tmpdir() + sep + `pythonShellFile${randomInt}.py`;
writeFileSync(filePath, code);

return PythonShell.run(filePath, options);
Expand Down
33 changes: 32 additions & 1 deletion test/test-python-shell.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import * as should from 'should';
import { PythonShell } from '..';
import { sep, join } from 'path';
import { EOL as newline } from 'os';
import { EOL as newline, tmpdir } from 'os';
import { existsSync, readFileSync, unlinkSync } from 'fs';
import { chdir, cwd } from 'process';

describe('PythonShell', function () {
Expand Down Expand Up @@ -124,6 +125,36 @@ describe('PythonShell', function () {
before(() => {
PythonShell.defaultOptions = {};
});
it('should create a temporary file in the OS temp directory before running', async function () {
const originalRun = PythonShell.run;
let capturedScriptPath = '';
let capturedOptions = null;

// Avoid spawning Python: we only verify temp file path generation and handoff.
(PythonShell as any).run = async (scriptPath, options) => {
capturedScriptPath = scriptPath;
capturedOptions = options;
return [];
};

const options = { mode: 'text' as const };
const code = 'print(\"hello from runString\")';

try {
await PythonShell.runString(code, options);

capturedScriptPath.should.startWith(tmpdir() + sep + 'pythonShellFile');
capturedScriptPath.should.endWith('.py');
existsSync(capturedScriptPath).should.be.true();
readFileSync(capturedScriptPath, 'utf8').should.eql(code);
capturedOptions.should.eql(options);
} finally {
if (capturedScriptPath && existsSync(capturedScriptPath)) {
unlinkSync(capturedScriptPath);
}
(PythonShell as any).run = originalRun;
}
});
it('should be able to execute a string of python code', function (done) {
PythonShell.runString('print("hello");print("world")', null).then(
(results) => {
Expand Down