如何使用IronPython中的标准库?

2024-03-29 14:56:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这个问题的前面加上一个前缀:不,设置IRONPYTHONPATH不是答案。

不管怎样。。。

我本来打算用IronPython代替Powershell来完成一个项目,但在我开始之前就已经被难住了。

我尝试做的第一件事就是使用os.path,结果是:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named os

经过一番周折,我终于发现可以通过手动将标准库添加到路径中来使用它:

import sys
sys.path.append(r"C:\Program Files\IronPython 2.7\Lib")
import os

然而,这是一个愚蠢的想法。在我的脚本中对python库的路径进行硬编码是一种100%有保证的方法,可以使它们在某个时刻不工作。

当我试图在Windows7计算机上使用脚本时,我几乎立刻发现了这一点,并且路径略有不同(“程序文件(x86)”。

所以,这里有几个问题:

1)为什么使用标准库如此困难?至少我认为VS和basic ipy.exe中的交互式提示会有这个功能。

2)如何确定iron python安装在哪个目录中,而不考虑我正在使用的系统?(IronPython安装程序可能设置了一个变量?)

这里只是一个注释;是的,我看到一些其他的帖子说“设置你的铁Python”。这没用。如果我有一台空白机器,这意味着我必须:

1)安装IronPython

2)运行一些疯狂的powershell脚本来搜索标准库的安装位置,并为其设置全局IRONPYTHONPATH变量。

3)运行python脚本

我在找更好的方法。

--

编辑:

我用它来做类似powershell的事情基本上是无关紧要的,但我试图实现如下目标:

import clr
from System.Management.Automation import RunspaceInvoke
import os

scriptRoot = os.getcwd()
runSpace = RunspaceInvoke()
cmdPath64 = os.join(scriptRoot, "..\java\...")
cmdPath32 = os.join(scriptRoot, "..\java\...")
proc = runSpace.Invoke("Get-WmiObject Win32_Processor ... ")
if proc.AddressWidth == 32:
  runSpace.Invoke(cmdPath32)
else:
  runSpace.Invoke(cmdPath64)

Tags: path方法import路径脚本标准ossys
3条回答

这是一个有点变通的方法,但是,鉴于ironpython的LIB目录安装在64位系统中的x86程序文件文件夹下,以及32位系统中的常规程序文件路径上,您可以这样做:

import sys
import System
if System.IntPtr.Size * 8 == 32: # detect if we are running on 32bit process
    sys.path.append(System.Environment.GetEnvironmentVariable("ProgramFiles") + "\IronPython 2.7\Lib")
else:
    sys.path.append(System.Environment.GetEnvironmentVariable("ProgramFiles(x86)") + "\IronPython 2.7\Lib")

import os # it works !!

在这里,我们使用%ProgramFiles%%ProgramFiles(x86)%来确定IronPython的安装路径。

引用维基百科关于%ProgramFiles%变量(link)的内容:

%ProgramFiles%

This variable points to Program Files directory, which stores all the installed program of Windows and others. The default on English-language systems is C:\Program Files. In 64-bit editions of Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)% which defaults to C:\Program Files (x86) and %ProgramW6432% which defaults to C:\Program Files. The %ProgramFiles% itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).

我发现为了确保所有东西都能为非开发人员的第三方工作,通常最好使用pyc.py来创建DLL和可执行文件。我经常创建一个python标准模块的DLL并在代码中引用它。在这个问题上看我以前的答案IronPython: EXE compiled using pyc.py cannot import module "os"

这很奇怪,因为如果您运行IronPython安装程序,然后运行C:\Program Files\IronPython 2.7\ipy.exeC:\Program Files (x86)\IronPython 2.7\ipy.exe,您不需要做任何事情就可以使用stdlib。

我的猜测是,你有不止一个IronPython,而且你运行的是错误的,但这只是因为我想不出会发生这种情况的另一个原因。它应该只是工作。

相关问题 更多 >