[英]How can I open the currently running script's .py file using IDLE in Python?
In a GUI app written in Python and Tkinter, I want to add a menu command which will open the source code of the *.py file in IDLE.在用 Python 和 Tkinter 编写的 GUI 应用程序中,我想添加一个菜单命令,它将在 IDLE 中打开 *.py 文件的源代码。 I also want it to be platform independent.我也希望它独立于平台。
I've tried using os.system
to open IDLE from Scripts folder of Python, but that would be platform dependent.我尝试使用 os.system 从os.system
的 Scripts 文件夹中打开 IDLE,但这取决于平台。 I couldn't find a way to get the Scripts folder of Python to make it independent.我找不到方法来获取 Python 的 Scripts 文件夹以使其独立。 How can I achieve this?我怎样才能做到这一点?
To open a file in an IDLE editor, the command line is要在 IDLE 编辑器中打开文件,命令行是
<python> -m idlelib <path>
where <python>
is the full path to a python executable or a name that resolves to such.其中<python>
是 python 可执行文件的完整路径或解析为此类的名称。 If you want to open IDLE with the same python that is running you python app, which is likely what you want, use the platform-independent sys.executable
.如果您想使用运行 python 应用程序的相同 python 打开 IDLE,这可能是您想要的,请使用与平台无关的sys.executable
。 The path to the source code for the running app is __file__
.正在运行的应用程序的源代码路径是__file__
。 This is one of the semi-hidden global variables when python runs a file.这是 python 运行文件时的半隐藏全局变量之一。 Or give the path to any other file.或提供任何其他文件的路径。
Whether you use os.system
or subprocess
is a different issue.无论您使用subprocess
还是os.system
是一个不同的问题。 The latter is more flexible.后者更灵活。 subprocess.run
replaces os.system
. subprocess.run
替换os.system
。 subprocess.Popen
should not block. subprocess.Popen
不应阻塞。 IDLE uses the latter to run user code. IDLE 使用后者来运行用户代码。
I tried some special way:我尝试了一些特殊的方法:
import idlelib.pyshell
import sys
sys.argv.clear()
sys.argv.append("")
sys.argv.append(fName)
idlelib.pyshell.main()
It works.有用。 But I don't know whether this way will generate some problems.但不知道这种方式会不会产生一些问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.