c# - os.access 在 IronPython 中为 os.F_OK 模式返回无用值

标签 c# python windows file ironpython

我有一堆 python 脚本,我试图在 IronPython 中使用它们(我需要 C# 功能),并且我在 os.access 方法方面遇到了一些问题。

当使用模式设置为 os.F_OK 的 os.access 方法(查看路径是否可以访问)时,我每次都会返回 False,即使 python 解释器为该目录返回 True 也是如此。但奇怪的是,使用 os.R_OK、os.W_OK 和 os.X_OK 模式调用的 os.access 方法返回 True。

这是我用来演示该问题的代码示例:

import os

d = ["C:\\", ".\\", "./", ".", "C:\\BOGUS_DIR"]

for path in d:
    print path
    try:
        print "access: %s"%os.access(path, os.F_OK)
        print "read: %s"%os.access(path, os.R_OK)
        print "write: %s"%os.access(path, os.W_OK)
        print "execute: %s"%os.access(path, os.X_OK)
        print "-------------------------"
    except Exception, e:
        print e

print "finished"

raw_input("")

结果:

C:\
access: False
read: True
write: True
execute: True
-------------------------
.\
access: False
read: True
write: True
execute: True
-------------------------
./
access: False
read: True
write: True
execute: True
-------------------------
.
access: False
read: True
write: True
execute: True
-------------------------
C:\BOGUS_DIR
access: False
[Errno 2] Could not find file 'C:\BOGUS_DIR'.
finished

为了更好地衡量,我在列表中添加了一个虚假目录(一个不存在的目录)。模式为 os.F_OK 的 os.access 返回 False(一如既往),但检查 os.R_OK 的调用会抛出异常(如预期)。

此外,我在 python 解释器中测试了 os.access 方法,效果很好。

我似乎找不到其他人遇到这个问题,这就是为什么我的第一个假设是我做了一些愚蠢的事情(或者错过了一些明显的事情)。我正在通过 Visual Studio 2010 运行 IronPython 代码,也许有什么干扰。

任何帮助将不胜感激。谢谢

最佳答案

首先,os.access 可能会产生误导 - 最好只是打开文件并捕获发生的任何异常。

IronPython 使用 os.F_OK 表示“此文件是否存在”,并将其归结为对 File.Exists() 的调用 - 对于目录返回 false。

This is a bug ,并应在 2.7.1 中修复。

关于c# - os.access 在 IronPython 中为 os.F_OK 模式返回无用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6823785/

相关文章:

c# - 通过 StringBuilder 为字符串添加字节顺序标记

c# - 将单例与依赖注入(inject)一起使用(CaSTLe Windsor)

c# - 在表单中处理自定义内存中控件

python - 为什么 Django 会为 auth.User.username 设置一个较短的外键最大长度?

windows - 捕获命令的输出并检查批处理脚本中的错误级别

c# - C# 中的委托(delegate)和 F# 中作为第一类值的函数有什么区别?

python - Google AppEngine 使用哪个 simplejson 模块?

python - asyncio.test_utils.run_briefly 到底是做什么的?

windows - 如何手动确定当前操作系统的代码页和区域设置

c - Visual-C++ 内联汇编程序编译不正确