无法导入crt.\u在python中通过ctypes打开

无法导入crt.\u在python中通过ctypes打开,python,subprocess,ctypes,Python,Subprocess,Ctypes,我正面临一个类似的问题,正如所描述的,使用了帖子中给出的答案。 我在Windows 64位计算机上使用Python2.7,并使用Python默认的ctypes。以上链接中给出的代码 pyfrom ctypes import * pycrt = cdll.msvcrt py_sopen = crt._sopen py_sopen.argtypes = (c_char_p, c_int, c_int, c_int) py_SH_DENYRW = 0x10 # from <share.h>

我正面临一个类似的问题,正如所描述的,使用了帖子中给出的答案。 我在Windows 64位计算机上使用Python2.7,并使用Python默认的ctypes。以上链接中给出的代码

pyfrom ctypes import *
pycrt = cdll.msvcrt
py_sopen = crt._sopen
py_sopen.argtypes = (c_char_p, c_int, c_int, c_int)
py_SH_DENYRW = 0x10 # from <share.h>
pyh = _sopen("C:\\1.txt", 0, _SH_DENYRW, 0)
print pyh
pyfrom ctypes导入*
pycrt=cdll.msvcrt
py_sopen=阴极射线管
py_sopen.argtypes=(c_char_p,c_int,c_int,c_int)
py_SH_DENYRW=0x10#从
pyh=_sopen(“C:\\1.txt”,0,_SH_DENYRW,0)
打印pyh
pyfrom ctypes导入* ^ 语法错误:无效语法

如果我将pyfrom ctypes import*更改为from ctypes import*,则py\u sopen=crt.\u sopen
名称错误:未定义名称“crt”

pyfrom ctypes import*
不是有效语法。它应该是来自ctypes导入的
*

不管是谁给你的密码乱七八糟。从每个变量名的开头删除
py
,它至少会运行,但我无法告诉您它是否达到了预期效果

from ctypes import *
crt = cdll.msvcrt
_sopen = crt._sopen
_sopen.argtypes = (c_char_p, c_int, c_int, c_int)
_SH_DENYRW = 0x10 # from <share.h>
h = _sopen("C:\\1.txt", 0, _SH_DENYRW, 0)
print h

我看到了链接,如果修复语法错误不是你的问题,那是什么?我突出显示了错误。我的原始版本与link的版本相同。所以,我认为这个ctypes可以解决这个问题。但是这个错误你读过答案了吗?此解决方案修复了您遇到的两个问题。我测试了代码,它运行时没有出现更多错误。不管文件是否打开,它总是在控制台中打印3。我在wordpad中打开1.txt,然后执行上面的代码,然后它也在打印3。那么wordpad不会以这个程序检查的方式保存文件“open”。如果使用python的
open
命令打开txt文件。在使用
之前,您将得到-1。请在其上关闭
filename = r"C:\python\test.txt"

f = open(filename, 'w')

from ctypes import *
crt = cdll.msvcrt
_sopen = crt._sopen
_sopen.argtypes = (c_char_p, c_int, c_int, c_int)
_SH_DENYRW = 0x10 # from <share.h>
h = _sopen(filename, 0, _SH_DENYRW, 0)
print h

f.close()

from ctypes import *
crt = cdll.msvcrt
_sopen = crt._sopen
_sopen.argtypes = (c_char_p, c_int, c_int, c_int)
_SH_DENYRW = 0x10 # from <share.h>
h = _sopen(filename, 0, _SH_DENYRW, 0)
print h
-1
3