我面临与here描述的类似问题,使用帖子中给出的答案。 我在Windows 64位机器上使用Python 2.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 import * ^ SyntaxError:语法无效
如果我从ctypes import * 将 pyfrom ctypes import * 更改为,那么 py_sopen = crt._sopen NameError:名称'crt'未定义
答案 0 :(得分:2)
pyfrom ctypes import *
不是有效的语法。它应该是from ctypes import *
谁给你的代码搞砸了。从每个变量名称的开头删除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
测试功能:
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