pythonclr
Ⅰ python调用另外一个python程序的结果
os.system只是运行,不返回结果。
用commands
import commands
txt = commands.getoutput('ls -al')
Ⅱ ironpython import clr clr是什么
微软DotNet平台下有个基础框架.netframework,里面有两个非常重要的组成部分:
类库
CLR,即Common Language Runtime(公共语言运行时),负责我们的.net程序运行托管
Ⅲ python是软件吗 为什么我在桌面上没有找到它 那我要运行它应该在哪找呢
安装个pycharm软件,就可以在上面运行.py程序了。你可以去pycharm官网下载免费版。
Ⅳ Python 有什么奇技淫巧
看看下面这些算不算1.元类(metaclass)PyPy的源码里有个pair和extendabletype"""Twomagictricksforclasses:classX:__metaclass__=extendabletype#insomeotherfileclass__extend__(X):#hthesecondtrick,whichletsyoubuildmethodswhose'self':class__extend__(pairtype(X,Y)):attribute=42defmethod((x,y),other,arguments):pair(x,y).attributepair(x,y).method(other,arguments)atgointothepair(),withtheusualrulesofmethod/attributeoverridingin(pairsof)subclasses.Formoreinformation,seetest_pairtype."""classextendabletype(type):"""Atypewithasyntaxtrick:'class__extend__(t)''t'insteadofcreatinganewsubclass."""def__new__(cls,name,bases,dict):ifname=='__extend__':forclsinbases:forkey,valueindict.items():ifkey=='__mole__':continue#?setattr(cls,key,value)returnNoneelse:returnsuper(extendabletype,cls).__new__(cls,name,bases,dict)defpair(a,b):"""Returnapairobject."""tp=pairtype(a.__class__,b.__class__)returntp((a,b))#={}defpairtype(cls1,cls2):"""type(pair(a,b))ispairtype(a.__class__,b.__class__)."""try:pair=pairtypecache[cls1,cls2]exceptKeyError:name='pairtype(%s,%s)'%(cls1.__name__,cls2.__name__)bases1=[pairtype(base1,cls2)forbase1incls1.__bases__]bases2=[pairtype(cls1,base2)forbase2incls2.__bases__]bases=tuple(bases1+bases2)or(tuple,)#'tuple':ultimatebasepair=pairtypecache[cls1,cls2]=extendabletype(name,bases,{})returnpair先说extendabletype。嘛其实注释已经说得听明白了,就是一个C#里面的partialclass的Python实现。然后是pair和pairtype。pairtype就是根据两个类创建一个新的类,这个类继承自使用这两个类的基类构造的pairtype(有点绕……)或者tuple。有啥用呢?可以拿来实现multimethod。class__extend__(pairtype(int,int)):deffoo((x,y)):print'int-int:%s-%s'%(x,y)class__extend__(pairtype(bool,bool)):defbar((x,y)):print'bool-bool:%s-%s'%(x,y)pair(False,True).foo()#prints'int-int:False,True'pair(123,True).foo()#prints'int-int:123,True'pair(False,True).bar()#prints'bool-bool:False,True'pair(123,True).bar()#Oops,nosuchmethod好像这个例子里元类只是个打辅助的角色,好玩的都在那个pair里……再换一个。classGameObjectMeta(type):def__new__(mcls,clsname,bases,_dict):fork,vin_dict.items():ifisinstance(v,(list,set)):_dict[k]=tuple(v)#mutableobjnotallowedcls=type.__new__(mcls,clsname,bases,_dict)all_gameobjects.add(cls)forbinbases:game_objects_hierarchy.add((b,cls))returncls@staticmethoddef_mp_gameobject_hierarchy():withopen('/dev/shm/gomap.dot','w')asf:f.write('digraph{\nrankdir=LR;\n')f.write('\n'.join(['"%s"->"%s";'%(a.__name__,b.__name__)fora,bingame_objects_hierarchy]))f.write('}')def__setattr__(cls,field,v):type.__setattr__(cls,field,v)iffieldin('ui_meta',):returnlog.warning('SetAttr:%s.%s=%s'%(cls.__name__,field,repr(v)))这个是从我写的三国杀游戏中提取的一段代码(点我签名上的链接)。大意就是把class上所有可变的容器都换成不可变的,然后记录下继承关系。曾经被这个问题坑过,class上的值是全局共享的,逻辑代码一不小心修改了class上的值,单机测试的时候是测不出来的,然后放到线上……就悲剧了……当时绞尽脑汁没有想到是这个问题硬生生的回滚了……发现了问题之后就加上了这个东西,不允许修改class上的东西。记录下继承关系是为了画类图。还有就是常用的做数据注入metadata={}defgen_metafunc(_for):defmetafunc(clsname,bases,_dict):meta_for=getattr(_for,clsname)meta_for.ui_meta=UIMetaDescriptor()ifmeta_forinmetadata:raiseException('%sui_metaredefinition!'%meta_for)metadata[meta_for]=_.thbimportcharacters__metaclass__=gen_metafunc(characters.sakuya)classSakuya:#于是这个就不是类了,而是作为数据存到了metadata这个dict里char_name=u'十六夜咲夜'port_image='thb-portrait-sakuya'figure_image='thb-figure-sakuya'miss_sound_effect='thb-cv-sakuya_miss'description=(u'|DB完全潇洒的PAD长十六夜咲夜体力:4|r\n\n'u'|G月时计|r:|B锁定技|r,准备阶段开始时,你执行一个额外的出牌阶段。\n\n'u'|G飞刀|r:你可以将一张装备牌当【弹幕】使用或打出。按此法使用的【弹幕】无距离限制。\n\n'u'|DB(画师:小D@星の妄想乡,CV:VV)|r')Ruby党不要喷,我知道你们可以做的更优雅……2.Python沙盒逃逸刷新三观的Python代码3.PEP302NewImportHook最近在把刚才提到的纯Python游戏向Unity引擎上移植。玩过Unity的就会知道,Unity的游戏的资源都是打包在一起的,没有单独的文件,Python解释器就不高兴了……于是写了importhook,用Unity提供的API来读py文件。#-*-coding:utf-8-*-#--stdlib--importimpimportsys#--thirdparty--#--own--fromclrimportUnityEngine,WarpGateController#--code--classUnityResourceImporter(object):known_builtin=('sys','imp','cStringIO','gevent_core','gevent_ares','gevent_util','gevent_semaphore','msgpack_packer','msgpack_unpacker','UnityEngine',)def__init__(self,bases,unity_loader):self.bases=basesself.last_fullname=''self.last_text=''self.last_ispkg=Falseself.unity_load=unity_loaderdeffind_mole(self,fullname,path=None):iffullnameinsys.moles:returnselfhead=fullname.split('.')[0]ifheadinself.known_builtin:returnNonerst=self.do_load_mole(fullname)ifrst:self.last_text,self.last_ispkg=rstself.last_fullname=fullnamereturnselfelse:returnNonedefload_mole(self,fullname):iffullnameinsys.moles:returnsys.moles[fullname]iffullname!=self.last_fullname:self.find_mole(fullname)try:code=self.last_textispkg=self.last_ispkgmod=sys.moles.setdefault(fullname,imp.new_mole(fullname))mod.__file__=""%fullnamemod.__loader__=selfifispkg:mod.__path__=[]mod.__package__=fullnameelse:mod.__package__=fullname.rpartition('.')[0]co=compile(code,mod.__file__,'exec')exec(co,mod.__dict__)returnmodexceptExceptionase:UnityEngine.Debug.LogError('Errorimporting%s%s'%(fullname,e))raiseImportError(e)defdo_load_mole(self,fullname):fn=fullname.replace('.','/')asset=self.try_load(fn+'.py')ifassetisnotNone:returnasset,Falseasset=self.try_load(fn+'/__init__.py')ifassetisnotNone:returnasset,Truedeftry_load(self,filename):forbinself.bases:asset=self.unity_load(b+filename)ifassetisnotNone:returnassetreturnNonesys.meta_path.append(UnityResourceImporter(['Python/THBattle/','Python/Site/','Python/Stdlib/',],WarpGateController.GetTextAsset))需要的extensionmole都静态编译到解释器里了,所以没考虑。4.可以批量执行操作的listclassBatchList(list):def__getattribute__(self,name):try:list_attr=list.__getattribute__(self,name)returnlist_attrexceptAttributeError:passreturnlist.__getattribute__(self,'__class__')(getattr(i,name)foriinself)def__call__(self,*a,**k):returnlist.__getattribute__(self,'__class__')(f(*a,**k)forfinself)classFoo(object):def__init__(self,v):self.value=vdeffoo(self):print'Foo!',self.valuefoo=Foo(1)foo.foo()#Foo!1foos=BatchList(Foo(i)foriinxrange(10))foos.value#BatchList([0,1,2,3,,9])foos.foo()#你能猜到的
Ⅳ python调用外部C#库的dll文件
importclr
importSystem
clr.AddReferenceToFile("SimpleHash.dll")
fromCommonimport*
classHashPy(SimpleHash):
def__init__(self):
pass
defHashCalc(self,arg1,arg2):
#strtobyte[]
arg1=System.Text.Encoding.Default.GetBytes(arg1)
arg2=System.Text.Encoding.Default.GetBytes(arg2)
returnSimpleHash.HashCalc(self,arg1,arg2)
audiobuff='
12345678
12345678
'
key='12345678'
printHashPy().HashCalc(audiobuff,key)
python ctype只能调用c/c++. 你要调用c#的dll 要用IronPython。如上面的例子
Ⅵ python是用c#来写的那岂不是还是微软的技术
python语言有个语言规范,有很多解释编译器实现版本
C实现的版本还叫python
java实现的版本叫jython
C#实现的好像叫ironpython
就比如C++,一样,有很多编译器实现,microsoft C++ compiler, intel c++ compiler,borland c++,g++.....
Ⅶ pythoncharm有哪些奇技淫巧
1. 元类(metaclass)
PyPy的源码里有个pair和extendabletype
"""
Two magic tricks for classes:
class X:
__metaclass__ = extendabletype
...
# in some other file...
class __extend__(X):
... # and here you can add new methods and class attributes to X
Mostly useful together with the second trick, which lets you build
methods whose 'self' is a pair of objects instead of just one:
class __extend__(pairtype(X, Y)):
attribute = 42
def method((x, y), other, arguments):
...
pair(x, y).attribute
pair(x, y).method(other, arguments)
This finds methods and class attributes based on the actual
class of both objects that go into the pair(), with the usual
rules of method/attribute overriding in (pairs of) subclasses.
For more information, see test_pairtype.
"""
class extendabletype(type):
"""A type with a syntax trick: 'class __extend__(t)' actually extends
the definition of 't' instead of creating a new subclass."""
def __new__(cls, name, bases, dict):
if name == '__extend__':
for cls in bases:
for key, value in dict.items():
if key == '__mole__':
continue
# XXX do we need to provide something more for pickling?
setattr(cls, key, value)
return None
else:
return super(extendabletype, cls).__new__(cls, name, bases, dict)
def pair(a, b):
"""Return a pair object."""
tp = pairtype(a.__class__, b.__class__)
return tp((a, b)) # tp is a subclass of tuple
pairtypecache = {}
def pairtype(cls1, cls2):
"""type(pair(a,b)) is pairtype(a.__class__, b.__class__)."""
try:
pair = pairtypecache[cls1, cls2]
except KeyError:
name = 'pairtype(%s, %s)' % (cls1.__name__, cls2.__name__)
bases1 = [pairtype(base1, cls2) for base1 in cls1.__bases__]
bases2 = [pairtype(cls1, base2) for base2 in cls2.__bases__]
bases = tuple(bases1 + bases2) or (tuple,) # 'tuple': ultimate base
pair = pairtypecache[cls1, cls2] = extendabletype(name, bases, {})
return pair
先说extendabletype。嘛 其实注释已经说得听明白了,就是一个C#里面的partial class的Python实现。
然后是pair和pairtype。pairtype就是根据两个类创建一个新的类,这个类继承自使用这两个类的基类构造的pairtype(有点绕……)或者tuple。
有啥用呢?可以拿来实现multimethod。
class __extend__(pairtype(int, int)):
def foo((x, y)):
print 'int-int: %s-%s' % (x, y)
class __extend__(pairtype(bool, bool)):
def bar((x, y)):
print 'bool-bool: %s-%s' % (x, y)
pair(False, True).foo() # prints 'int-int: False, True'
pair(123, True).foo() # prints 'int-int: 123, True'
pair(False, True).bar() # prints 'bool-bool: False, True'
pair(123, True).bar() # Oops, no such method
好像这个例子里元类只是个打辅助的角色,好玩的都在那个pair里……
再换一个。
class GameObjectMeta(type):
def __new__(mcls, clsname, bases, _dict):
for k, v in _dict.items():
if isinstance(v, (list, set)):
_dict[k] = tuple(v) # mutable obj not allowed
cls = type.__new__(mcls, clsname, bases, _dict)
all_gameobjects.add(cls)
for b in bases:
game_objects_hierarchy.add((b, cls))
return cls
@staticmethod
def _mp_gameobject_hierarchy():
with open('/dev/shm/gomap.dot', 'w') as f:
f.write('digraph {\nrankdir=LR;\n')
f.write('\n'.join([
'"%s" -> "%s";' % (a.__name__, b.__name__)
for a, b in game_objects_hierarchy
]))
f.write('}')
def __setattr__(cls, field, v):
type.__setattr__(cls, field, v)
if field in ('ui_meta', ):
return
log.warning('SetAttr: %s.%s = %s' % (cls.__name__, field, repr(v)))
这个是从我写的三国杀游戏中提取的一段代码(点我签名上的链接)。大意就是把class上所有可变的容器都换成不可变的,然后记录下继承关系。
曾经被这个问题坑过,class上的值是全局共享的,逻辑代码一不小心修改了class上的值,单机测试的时候是测不出来的,然后放到线上……就悲剧了……当时绞尽脑汁没有想到是这个问题硬生生的回滚了……发现了问题之后就加上了这个东西,不允许修改class上的东西。
记录下继承关系是为了画类图。
还有就是常用的做数据注入
metadata = {}
def gen_metafunc(_for):
def metafunc(clsname, bases, _dict):
meta_for = getattr(_for, clsname)
meta_for.ui_meta = UIMetaDescriptor()
if meta_for in metadata:
raise Exception('%s ui_meta redefinition!' % meta_for)
metadata[meta_for] = _dict
return metafunc
from gamepack.thb import characters
__metaclass__ = gen_metafunc(characters.sakuya)
class Sakuya:
# 于是这个就不是类了, 而是作为数据存到了metadata这个dict里
char_name = u'十六夜咲夜'
port_image = 'thb-portrait-sakuya'
figure_image = 'thb-figure-sakuya'
miss_sound_effect = 'thb-cv-sakuya_miss'
description = (
u'|DB完全潇洒的PAD长 十六夜咲夜 体力:4|r\n\n'
u'|G月时计|r:|B锁定技|r,准备阶段开始时,你执行一个额外的出牌阶段。\n\n'
u'|G飞刀|r:你可以将一张装备牌当【弹幕】使用或打出。按此法使用的【弹幕】无距离限制。\n\n'
u'|DB(画师:小D@星の妄想乡,CV:VV)|r'
)
Ruby党不要喷,我知道你们可以做的更优雅……
2. Python沙盒逃逸
刷新三观的Python代码
3. PEP302 New Import Hook
最近在把刚才提到的纯Python游戏向Unity引擎上移植。
玩过Unity的就会知道,Unity的游戏的资源都是打包在一起的,没有单独的文件,Python解释器就不高兴了……于是写了import hook,用Unity提供的API来读py文件。
# -*- coding: utf-8 -*-
# -- stdlib --
import imp
import sys
# -- third party --
# -- own --
from clr import UnityEngine, WarpGateController
# -- code --
class UnityResourceImporter(object):
known_builtin = (
'sys',
'imp',
'cStringIO',
'gevent_core',
'gevent_ares',
'gevent_util',
'gevent_semaphore',
'msgpack_packer',
'msgpack_unpacker',
'UnityEngine',
)
def __init__(self, bases, unity_loader):
self.bases = bases
self.last_fullname = ''
self.last_text = ''
self.last_ispkg = False
self.unity_load = unity_loader
def find_mole(self, fullname, path=None):
if fullname in sys.moles:
return self
head = fullname.split('.')[0]
if head in self.known_builtin:
return None
rst = self.do_load_mole(fullname)
if rst:
self.last_text, self.last_ispkg = rst
self.last_fullname = fullname
return self
else:
return None
def load_mole(self, fullname):
if fullname in sys.moles:
return sys.moles[fullname]
if fullname != self.last_fullname:
self.find_mole(fullname)
try:
code = self.last_text
ispkg = self.last_ispkg
mod = sys.moles.setdefault(fullname, imp.new_mole(fullname))
mod.__file__ = "<UnityResource: %s>" % fullname
mod.__loader__ = self
if ispkg:
mod.__path__ = []
mod.__package__ = fullname
else:
mod.__package__ = fullname.rpartition('.')[0]
co = compile(code, mod.__file__, 'exec')
exec(co, mod.__dict__)
return mod
except Exception as e:
UnityEngine.Debug.LogError('Error importing %s %s' % (fullname, e))
raise ImportError(e)
def do_load_mole(self, fullname):
fn = fullname.replace('.', '/')
asset = self.try_load(fn + '.py')
if asset is not None:
return asset, False
asset = self.try_load(fn + '/__init__.py')
if asset is not None:
return asset, True
def try_load(self, filename):
for b in self.bases:
asset = self.unity_load(b + filename)
if asset is not None:
return asset
return None
sys.meta_path.append(UnityResourceImporter([
'Python/THBattle/',
'Python/Site/',
'Python/Stdlib/',
], WarpGateController.GetTextAsset))
需要的extension mole都静态编译到解释器里了,所以没考虑。
4. 可以批量执行操作的list
class BatchList(list):
def __getattribute__(self, name):
try:
list_attr = list.__getattribute__(self, name)
return list_attr
except AttributeError:
pass
return list.__getattribute__(self, '__class__')(
getattr(i, name) for i in self
)
def __call__(self, *a, **k):
return list.__getattribute__(self, '__class__')(
f(*a, **k) for f in self
)
class Foo(object):
def __init__(self, v):
self.value = v
def foo(self):
print 'Foo!', self.value
foo = Foo(1)
foo.foo() # Foo! 1
foos = BatchList(Foo(i) for i in xrange(10))
foos.value # BatchList([0, 1, 2, 3, ..., 9])
foos.foo() # 你能猜到的
这个其实不算很黑魔法了,只是感觉很好用也有些危险,所以放上来。
暂时就想到这么多了,以后发现了再补。
Ⅷ 分析C#和python的优劣。必点赞。
C#实际上来风格是类似java的,可以说的c++和源java的结合体,做windows平台下应用,或者asp.net都挺好,但是仅限于windows,不能跨平台。python所有平台通用,一个python代码基本上可以不改在三种操作系统上用,除了调某系统特有api时不行,python适合写工具,比如爬虫,扫描器,做运维,游戏后台,现在的flask和django框架做web后台也不错,python还有一个重要应用在科学计算,比如机器学习,数据挖掘。python的代码简洁,但是速度慢,存在全局锁并发会有些麻烦,c#代码量大,但是速度快不少,作为编译型语言并发较容易。
Ⅸ python pycurl有哪些参数
#!/usr/bin/env python2
#encoding=utf8
import pycurl
import StringIO
# 安装pycurl到http://pycurl.sourceforge.net/这里去找.
# 在windows安装的话http://pycurl.sourceforge.net/download/ , 看你使用的版本决定下载那个,我在 windows使用的是.4, 所以下载 pycurl-ssl-7.15.5.1.win32-py2.4.exe 。
def test(debug_type, debug_msg):
print "debug(%d): %s" % (debug_type, debug_msg)
def postFile(url,post_file):
#print pycurl.version_info()
#这个函数创建一个同 libcurl中的CURL处理器相对应的Curl对象.Curl对象自动的设置CURLOPT_VERBOSE为0, CURLOPT_NOPROGRESS为1,提供一个默认的CURLOPT_USERAGENT和设置CURLOPT_ERRORBUFFER指向一个私有的错误缓冲区.
c = pycurl.Curl() #创建一个同libcurl中的CURL处理器相对应的Curl对象
b = StringIO.StringIO()
#c.setopt(c.POST, 1)
c.setopt(pycurl.URL, url) #设置要访问的网址 url = "http://www.cnn.com"
#写的回调
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.setopt(pycurl.FOLLOWLOCATION, 1) #参数有1、2
#最大重定向次数,可以预防重定向陷阱
c.setopt(pycurl.MAXREDIRS, 5)
#连接超时设置
c.setopt(pycurl.CONNECTTIMEOUT, 60) #链接超时
# c.setopt(pycurl.TIMEOUT, 300) #下载超时
# c.setopt(pycurl.HEADER, True)
# c.setopt(c.HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded","X-Requested-With:XMLHttpRequest","Cookie:"+set_cookie[0]])
#模拟浏览器
c.setopt(pycurl.USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)")
# c.setopt(pycurl.AUTOREFERER,1)
# c.setopt(c.REFERER, url)
# cookie设置
# Option -b/--cookie <name=string/file> Cookie string or file to read cookies from
# Note: must be a string, not a file object.
# c.setopt(pycurl.COOKIEFILE, "cookie_file_name")
# Option -c/--cookie-jar Write cookies to this file after operation
# Note: must be a string, not a file object.
# c.setopt(pycurl.COOKIEJAR, "cookie_file_name")
# Option -d/--data HTTP POST data
post_data_dic = {"name":"value"}
c.setopt(c.POSTFIELDS, urllib.urlencode(post_data_dic))
#设置代理
# c.setopt(pycurl.PROXY, ‘http://11.11.11.11:8080′)
# c.setopt(pycurl.PROXYUSERPWD, ‘aaa:aaa’)
#不明确作用
# c.setopt(pycurl.HTTPPROXYTUNNEL,1) #隧道代理
# c.setopt(pycurl.NOSIGNAL, 1)
#设置post请求, 上传文件的字段名 上传的文件
#post_file = "/home/ubuntu/avatar.jpg"
c.setopt(c.HTTPPOST, [("textname", (c.FORM_FILE, post_file))])
# 调试回调.调试信息类型是一个调试信 息的整数标示类型.在这个回调被调用时VERBOSE选项必须可用
# c.setopt(c.VERBOSE, 1) #verbose 详细
# c.setopt(c.DEBUGFUNCTION, test)
# f = open("body", "wb")
# c.setopt(c.WRITEDATA, f)
# h = open("header", "wb")
# c.setopt(c.WRITEHEADER, h)
# print "Header is in file 'header', body is in file 'body'"
# f.close()
# h.close()
# c.setopt(c.NOPROGRESS, 0)
# c.setopt(c.PROGRESSFUNCTION, progress)
# c.setopt(c.OPT_FILETIME, 1)
#访问,阻塞到访问结束
c.perform() #执行上述访问网址的操作
print "HTTP-code:", c.getinfo(c.HTTP_CODE) #打印出 200(HTTP状态码)
print "Total-time:", c.getinfo(c.TOTAL_TIME)
print "Download speed: %.2f bytes/second" % c.getinfo(c.SPEED_DOWNLOAD)
print "Document size: %d bytes" % c.getinfo(c.SIZE_DOWNLOAD)
print "Effective URL:", c.getinfo(c.EFFECTIVE_URL)
print "Content-type:", c.getinfo(c.CONTENT_TYPE)
print "Namelookup-time:", c.getinfo(c.NAMELOOKUP_TIME)
print "Redirect-time:", c.getinfo(c.REDIRECT_TIME)
print "Redirect-count:", c.getinfo(c.REDIRECT_COUNT)
# epoch = c.getinfo(c.INFO_FILETIME)
#print "Filetime: %d (%s)" % (epoch, time.ctime(epoch))
html = b.getvalue()
print(html)
b.close()
c.close()
Ⅹ Python,没有接触过这个语言,请问大神,no mole called clr
no mole called clr
包都没有啊,肯定运行不起来啦 。
CLR,即Common Language Runtime(公共语言运行时),负责我们的.net程序运行托管。
你在网上搜下clr这个包,然后安装了