调试sys.path的修改

编程入门 行业动态 更新时间:2024-10-26 18:21:29
本文介绍了调试sys.path的修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有些库似乎修改了我的sys.path,尽管我不想更改它.

Some library seems to modify my sys.path, although I don't want ìt to be changed.

如何找到更改sys.path的python代码行?

How can I find the python code line which alters sys.path?

相关

  • 在哪里替换sys.path?
推荐答案

首先导入的内容之一是sitecustomize和usercustomize模块.您可以将sys.path替换为记录所有所做更改的自定义列表实现.

One of the first things imported is the sitecustomize and usercustomize modules; you could replace sys.path with a custom list implementation that records all changes being made.

首先,找到放置usercustomize或sitecustomize模块的位置; site模块可以告诉您将第一个放在哪里:

First, find where to place a usercustomize or sitecustomize module; the site module can tell you where to place the first:

python -m site --user-site

如果该目录尚不存在,请创建该目录,并在其中放入usercustomize.py:

If that directory doesn't exist yet, create it and in it put a usercustomize.py with:

import sys class VerboseSysPath(list): def croak(self, action, args): frame = sys._getframe(2) print('sys.path.{}{} from {}:{}'.format( action, args, frame.f_code.co_filename, frame.f_lineno)) def insert(self, *args): self.croak('insert', args) return super(VerboseSysPath, self).insert(*args) def append(self, *args): self.croak('append', args) return super(VerboseSysPath, self).append(*args) def extend(self, *args): self.croak('extend', args) return super(VerboseSysPath, self).extend(*args) def pop(self, *args): self.croak('pop', args) return super(VerboseSysPath, self).pop(*args) def remove(self, *args): self.croak('remove', args) return super(VerboseSysPath, self).pop(*args) def __delitem__(self, *args): self.croak('__delitem__', args) return super(VerboseSysPath, self).__delitem__(*args) def __setitem__(self, *args): self.croak('__setitem__', args) return super(VerboseSysPath, self).__setitem__(*args) def __setslice__(self, *args): self.croak('__setslice__', args) return super(VerboseSysPath, self).__setslice__(*args) sys.path = VerboseSysPath(sys.path)

现在,这将抱怨所有试图更改sys.path列表的尝试.

This now will complain about all attempts at altering the sys.path list.

演示,以上内容放置在site-packages/sitecustomize.py或`python -m site --user-site`/usercustomize.py模块中:

Demo, with the above placed in either the site-packages/sitecustomize.py or `python -m site --user-site`/usercustomize.py modules:

$ cat test.py import sys sys.path.append('') $ bin/python test.py sys.path.append('',) from test.py:3

更多推荐

调试sys.path的修改

本文发布于:2023-11-23 21:16:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622884.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:sys   path

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!