IronPython的C#或其他.NET等效核心Python模块?

1 投票
2 回答
2036 浏览
提问于 2025-04-15 15:48

我想在 .net 上编译和发布一些与 IronPython 兼容的 Python 程序,但我对 .net 还不太熟悉,因此遇到了一些与特定 Python 模块相关的错误。有一个工具可以将代码编译成低级的 .net 格式,效果不错,但在处理一些常用库时却出现了错误;在解释器中能运行的代码不一定能成功编译。例如,下面的代码使用了基本模块 shutilgetpassosgetpass.getuser() 会返回一个用户名,类型是字符串。shutil 提供了很多功能,其中包括一个复制文件的功能(不过我可以用纯 Python 重写这个功能并成功编译),而 os 则用于获取文件夹信息、创建目录和删除文件。我该如何调整以下内容,完全或部分使用 .net 原生的库呢?如果有人用过 IronPython 来学习 .net,任何相关的建议都非常感谢。

import shutil
import os
import getpass

uname = getpass.getuser()

folders = ["/users/"+uname+"/location", "/users/"+uname+"/other_location"]

for folder in folders:
    for root, dir, files in os.walk(folder):
        for file in files:
            file_name = os.path.join(root, file)
            time_stamp = os.stat(file_name).st_mtime
            time_dict[time_stamp] = file_name
            working_list.append(time_stamp)


def sync_up():
    for item in working_list:
        if item not in update_list:
            os.remove(item)
        else:
            shutil.copy2(item, some_other_folder)

def cp_function(target=some_folder):
    if os.path.exists(target):
        sync_up()
    else:
        try:
            os.mkdir(target)
            sync_up()
        except:
            print """error connecting
            """

2 个回答

0

对于 os 模块,你可以使用 nt 模块,它提供了一些和 os 相同的功能,比如 statremovemkdir。此外,它还包括其他一些功能,比如 environgetcwdchdirpopen

举个例子:

» import nt
» nt.getcwd()
'C:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\IDE'

不过,这个实现并不完整,所以很遗憾,它没有 pathwalk 这些功能。如果需要这些功能,你可能需要使用 .NET 的 System.IO,正如 gimel 提到的

2

在.NET中,osshutil的替代品在System.IO命名空间里。

System.IO命名空间包含了一些类型,可以用来读取和写入文件以及数据流,还有一些类型提供基本的文件和目录支持。

对于大多数文件操作,可以尝试使用System.IO.File的方法。关于目录的信息,可以通过System.IO.Directory来获取。

我不知道有没有和os.walk完全相同的替代方法,可以试试使用GetDirectoriesGetFiles方法来自己构建一个目录遍历器。在Directory.GetDirectories(String)文档中有一个叫RecursiveFileProcessor的例子。

获取当前登录用户的用户名的简单方法,可以使用System.Environment.UserName属性。

下面是一个简单的交互式IronPython示例:

>>> import clr
>>> from System import Environment
>>> Environment.UserName
'gimel'
>>> from System import IO
>>> IO.Directory.GetCreationTimeUtc('c:/')
<System.DateTime object at 0x000000000000002B [02/07/2006 12:53:25]>
>>> IO.Directory.GetLastWriteTimeUtc('c:/')
<System.DateTime object at 0x000000000000002C [09/11/2009 08:15:32]>
>>> IO.Directory.GetDirectories('C:/').Count
24
>>> help(IO.File.Copy)
Help on built-in function Copy:

Copy(...)
    Copy(str sourceFileName, str destFileName, bool overwrite)

        Copies an existing file to a new file.
         Overwriting a file of the same name is allowed.
...

撰写回答