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這個包,然後安裝了