我想编译和分发(在.net上)一些与IronPython配合良好的python程序,但我是.net的新手,并且遇到了与特定python模块相关的错误。有一个实用程序可以编译到低级别.net并且运行良好,但在处理公共库时遇到错误;在解释器中运行的代码不一定编译。例如,以下内容利用了基本模块shutil
,getpass
和os
。 getpass.getuser()
以字符串形式返回用户名。 shutil
提供了一个复制功能(虽然我可以在纯python中重写并开始编译),os
用于获取文件夹信息,制作目录和取消链接文件。我可以如何在整个或任何部分中调整以下几行中的内容,以仅使用.net本机库?如果有人使用IronPython作为从python到学习.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
"""
答案 0 :(得分:2)
.NET中的os
(和shutil
)替换位于System.IO
namespace。
System.IO命名空间包含允许读写文件和数据流的类型,以及提供基本文件和目录支持的类型。
对于大多数文件文件操作,请尝试System.IO.File
class的方法。
目录信息可通过System.IO.Directory
class获得。
我不知道原生os.walk
替代方案,请尝试使用GetDirectories
和GetFiles
方法构建自己的目录漫游器。 Directory.GetDirectories(String)
doc中有一个 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.
...
答案 1 :(得分:0)
对于os
模块,您可以使用nt
模块,该模块提供与os
相同的一些功能,包括stat
,remove
和{{ 1}}。 (它还包括mkdir
,environ
,getcwd
和chdir
等其他内容。)
例如:
popen
但是,实施方式不完整,不幸的是,它没有» import nt
» nt.getcwd()
'C:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\IDE'
或path
。对于那些,您可能需要使用.NET的walk
作为gimel suggests。