From e53e0074f24f3bf859df185c2fc7e5621767384b Mon Sep 17 00:00:00 2001 From: AC Date: Sun, 11 Oct 2026 10:37:44 +0800 Subject: [PATCH] stdlib: resolve absolute script paths independently of sys.path --- stdlib/stdlib.go | 4 ++++ stdlib/stdlib_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 stdlib/stdlib_test.go diff --git a/stdlib/stdlib.go b/stdlib/stdlib.go index 7d1fb811..a99ab262 100644 --- a/stdlib/stdlib.go +++ b/stdlib/stdlib.go @@ -229,6 +229,10 @@ var defaultPaths = []py.Object{ func resolveRunPath(runPath string, opts py.CompileOpts, pathObjs []py.Object, tryPath func(pyPath string) (bool, error)) error { runPath = strings.TrimSuffix(runPath, "/") + if filepath.IsAbs(runPath) { + // Absolute paths are independent of the configured search directories. + pathObjs = []py.Object{py.String("")} + } var ( err error diff --git a/stdlib/stdlib_test.go b/stdlib/stdlib_test.go new file mode 100644 index 00000000..f0f4f361 --- /dev/null +++ b/stdlib/stdlib_test.go @@ -0,0 +1,34 @@ +// Copyright 2026 The go-python Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package stdlib + +import ( + "os" + "path/filepath" + "testing" + + "github.com/go-python/gpython/py" +) + +func TestRunFileAbsolutePath(t *testing.T) { + filename := filepath.Join(t.TempDir(), "script.py") + if err := os.WriteFile(filename, []byte("value = 42\n"), 0600); err != nil { + t.Fatal(err) + } + for _, useSysPaths := range []bool{false, true} { + ctx := NewContext(py.DefaultContextOpts()) + defer ctx.Close() + // Absolute paths must work even without any search directories. + ctx.Store().MustGetModule("sys").Globals["path"] = py.NewList() + module, err := py.RunFile(ctx, filename, py.CompileOpts{UseSysPaths: useSysPaths}, nil) + if err != nil { + t.Errorf("UseSysPaths=%v: %v", useSysPaths, err) + continue + } + if module.Globals["value"] != py.Int(42) { + t.Errorf("UseSysPaths=%v: script was not executed", useSysPaths) + } + } +}