本文整理汇总了Python中dir函数的典型用法代码示例。如果您正苦于以下问题:Python dir函数的具体用法?Python dir怎么用?Python dir使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dir函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: example2
def example2():
"creation of a new file using advanced IfcDocument object"
ifc = IfcDocument("/home/yorik/test2.ifc")
ifc.Name = "Test Project"
ifc.Owner = "Yorik van Havre"
ifc.Organization = "FreeCAD"
w1 = ifc.addWall( ifc.addExtrudedPolyline([(0,0,0),(0,200,0),(5000,200,0),(5000,0,0),(0,0,0)], (0,0,3500)) )
ifc.addWall( ifc.addExtrudedPolyline([(0,200,0),(0,2000,0),(200,2000,0),(200,200,0),(0,200,0)],(0,0,3500)) )
ifc.addWall( ifc.addExtrudedPolyline([(0,2000,0),(0,2200,0),(5000,2200,0),(5000,2000,0),(0,2000,0)],(0,0,3500)) )
ifc.addWall( ifc.addExtrudedPolyline([(5000,200,0),(5000,2000,0),(4800,2000,0),(4800,200,0),(5000,200,0)],(0,0,3500)) )
ifc.addWall( ifc.addFacetedBrep([[[(0,0,0),(100,0,0),(100,-1000,0),(0,-1000,0)]],
[[(0,0,0),(100,0,0),(100,0,1000),(0,0,1000)]],
[[(0,0,0),(0,0,1000),(0,-1000,1000),(0,-1000,0)]],
[[(0,-1000,0),(0,-1000,1000),(100,-1000,1000),(100,-1000,0)]],
[[(100,-1000,0),(100,-1000,1000),(100,0,1000),(100,0,0)]],
[[(0,0,1000),(0,-1000,1000),(100,-1000,1000),(100,0,1000)]]]) )
ifc.addStructure( "IfcColumn", ifc.addExtrudedPolyline([(0,0,0),(0,-200,0),(-500,-200,0),(-500,0,0),(0,0,0)], (0,0,3500)) )
ifc.addWindow( "IfcDoor", 200, 200, ifc.addExtrudedPolyline([(200,200,0),(200,400,0),(400,400,0),(400,200,0),(200,200,0)], (0,0,200)), w1 )
ifc.write()
print dir(ifc._fileobject)
print ifc._fileobject.by_type("IfcDoor")
w = ifc._fileobject.by_type("IfcDoor")[0]
print w
print dir(w)
print w.is_a("IfcDoor")
for i in range(w.get_argument_count()):
print i,": ",w.get_argument_name(i)," : ",w.get_argument(i)
示例2: __init__
def __init__(self, fn='depthFirstSearch', prob='PositionSearchProblem', heuristic='nullHeuristic'):
# Warning: some advanced Python magic is employed below to find the right functions and problems
# Get the search function from the name and heuristic
if fn not in dir(search):
raise AttributeError, fn + ' is not a search function in search.py.'
func = getattr(search, fn)
if 'heuristic' not in func.func_code.co_varnames:
print('[SearchAgent] using function ' + fn)
self.searchFunction = func
else:
if heuristic in globals().keys():
heur = globals()[heuristic]
elif heuristic in dir(search):
heur = getattr(search, heuristic)
else:
raise AttributeError, heuristic + ' is not a function in searchAgents.py or search.py.'
print('[SearchAgent] using function %s and heuristic %s' % (fn, heuristic))
# Note: this bit of Python trickery combines the search algorithm and the heuristic
self.searchFunction = lambda x: func(x, heuristic=heur)
# Get the search problem type from the name
if prob not in globals().keys() or not prob.endswith('Problem'):
raise AttributeError, prob + ' is not a search problem type in SearchAgents.py.'
self.searchType = globals()[prob]
print('[SearchAgent] using problem type ' + prob)
示例3: expose
def expose(self, name, new_name=None, position=-1):
"""Expose an attribute from a filter of the minipeline.
Once called, the pipeline instance has a new Set/Get set of methods to
access directly the corresponding method of one of the filter of the
pipeline.
Ex: p.expose( "Radius" )
p.SetRadius( 5 )
p.GetRadius( 5 )
By default, the attribute usable on the pipeline instance has the same
name than the one of the filter, but it can be changed by providing a
value to new_name.
The last filter of the pipeline is used by default, but another one may
be used by giving its position.
Ex: p.expose("Radius", "SmoothingNeighborhood", 2)
p.GetSmoothingNeighborhood()
"""
if new_name is None:
new_name = name
src = self.filters[position]
ok = False
set_name = "Set" + name
if set_name in dir(src):
setattr(self, "Set" + new_name, getattr(src, set_name))
ok = True
get_name = "Get" + name
if get_name in dir(src):
setattr(self, "Get" + new_name, getattr(src, get_name))
ok = True
if not ok:
raise RuntimeError(
"No attribute %s at position %s." %
(name, position))
示例4: test_strategies_names_introspection
def test_strategies_names_introspection(self):
sd = StrategyDict()
sd.strategy("first", "abc")(lambda val: "abc" + val)
sd.strategy("second", "def")(lambda val: "def" + val) # Neglect 2nd name
sd.strategy("third", "123")(lambda val: "123" + val) # Neglect 2nd name
# Nothing new here: strategies do what they should...
assert sd("x") == "abcx"
assert sd.default("p") == "abcp"
assert sd.first("w") == "abcw" == sd["first"]("w")
assert sd.second("zsc") == "defzsc" == sd["second"]("zsc")
assert sd.third("blah") == "123blah" == sd["third"]("blah")
assert sd.abc("y") == "abcy" == sd["abc"]("y")
assert sd["def"]("few") == "deffew"
assert sd["123"]("lots") == "123lots"
# Valid names for attributes
all_names = {"first", "second", "third", "abc", "def", "123"}
assert all(name in dir(sd) for name in all_names)
assert all(name in vars(sd) for name in all_names)
assert "default" in dir(sd)
assert "default" in vars(sd)
all_keys_tuples = sd.keys()
all_keys = reduce(operator.concat, all_keys_tuples)
assert set(all_keys) == all_names # Default not in keys
assert set(all_keys_tuples) == {("first", "abc"),
("second", "def"),
("third", "123")}
# First name is the __name__
assert sd["abc"].__name__ == "first"
assert sd["def"].__name__ == "second"
assert sd["123"].__name__ == "third"
示例5: sciopero_scraper
def sciopero_scraper():
"""
This function is used to generate the requests for URL containing data.
It's a generator which returns always a sciopero dict, with at least its id.
"""
min_id, max_id = find_id_range()
#print max_id
print 'scraping from %d to %d' % (min_id, max_id)
for i in xrange(min_id, max_id):
try:
resp = requests.get(sciopero_prefix % str(i))
except Exception as e:
print type(e)
print e
print dir(e)
exit()
print "Sleeping for %s seconds (requests)" % (SLEEP_TIME or 0)
time.sleep(SLEEP_TIME or 0)
if resp.status_code == 500 or 'HTTP Status 500' in resp.text:
continue
#print '%s%s' % (sciopero_prefix, str(i))
yield parse_sciopero(resp.content, i)
示例6: get_config
def get_config(config_path):
__import__('errbot.config-template') # - is on purpose, it should not be imported normally ;)
template = sys.modules['errbot.config-template']
config_fullpath = config_path
if not path.exists(config_fullpath):
log.error(
'I cannot find the file %s \n'
'(You can change this path with the -c parameter see --help)' % config_path
)
log.info(
'You can use the template %s as a base and copy it to %s. \nYou can then customize it.' % (
path.dirname(template.__file__) + sep + 'config-template.py', config_path + sep)
)
exit(-1)
# noinspection PyBroadException
try:
config = __import__(path.splitext(path.basename(config_fullpath))[0])
diffs = [item for item in set(dir(template)) - set(dir(config)) if not item.startswith('_')]
if diffs:
log.error('You are missing configs defined from the template :')
for diff in diffs:
log.error('Missing config : %s' % diff)
exit(-1)
except Exception as _:
log.exception('I could not import your config from %s, please check the error below...' % config_fullpath)
exit(-1)
log.info('Config check passed...')
return config
示例7: convert_dir
def convert_dir( fill = None, dirname = '.', stroke = None, strokeWidth = None, dest = None):
files = [ f for f in os.listdir(dirname) if f[-3:] == 'svg']
print "{0} SVG Files: ".format(len(files))
print '\n'.join(files)
print "Converting fill to: {0}{1}{2}"\
.format(fill,
", stroke to {0}".format(stroke) if stroke else '',
", strokeWidth to {0}".format(strokeWidth) if strokeWidth else '')
if dest == None:
dest = ("{0}-fill{1}{2}"\
.format(fill,
"-{0}-stroke".format(stroke) if stroke else '',
"-{0}-width".format(strokeWidth) if strokeWidth else '') )
if not os.path.isdir(dest):
os.mkdir(dest)
for f in files:
tree = svgparser.parse(os.path.join(dirname,f))
elts = svgu.list_elements(tree)
for e in elts:
if 'set_fill' in dir(e) and fill:
e.set_fill(fill)
if 'set_stroke' in dir(e) and stroke:
e.set_stroke(stroke)
if 'set_stroke_width' in dir(e) and strokeWidth:
e.set_stroke_width("{0}px".format(strokeWidth))
out = os.path.join(dest, f)
tree.save(out)
示例8: recommendCompletionsFor
def recommendCompletionsFor(self, word):
parts = word.split('.')
if len(parts) > 1:
# has a . so it must be a module or class or something
# using eval, which shouldn't normally have side effects
# unless there's descriptors/metaclasses doing some nasty
# get magic
objname = '.'.join(parts[:-1])
try:
obj = eval(objname, self.locals)
except:
return None, 0
wordlower = parts[-1].lower()
if wordlower == '':
# they just punched in a dot, so list all attributes
# that don't look private or special
prefix = '.'.join(parts[-2:])
check = [
(prefix+_method)
for _method
in dir(obj)
if _method[:1] != '_' and _method.lower().startswith(wordlower)
]
else:
# they started typing the method name
check = filter(lambda s:s.lower().startswith(wordlower), dir(obj))
else:
# no dots, must be in the normal namespaces.. no eval necessary
check = sets.Set(dir(__builtins__))
check.update(keyword.kwlist)
check.update(self.locals)
wordlower = parts[-1].lower()
check = filter(lambda s:s.lower().startswith(wordlower), check)
check.sort()
return check, 0
示例9: test_methods
def test_methods(self):
weaksetmethods = dir(WeakSet)
for method in dir(set):
if method == 'test_c_api' or method.startswith('_'):
continue
self.assertIn(method, weaksetmethods,
"WeakSet missing method " + method)
示例10: testRecusiveNesting
def testRecusiveNesting(self):
l = []
d = {1:l}
i = a_classic_class()
i.attr = d
l.append(i)
buf = self.archiverClass.archivedDataWithRootObject_(l)
self.assertIsInstance(buf, NSData)
v = self.unarchiverClass.unarchiveObjectWithData_(buf)
self.assertEqual(len(v), 1)
self.assertEqual(dir(v[0]), dir(i))
self.assertEqual(list(v[0].attr.keys()), [1])
if self.isKeyed:
self.assertIs(v[0].attr[1], v)
else:
# See 'TestArchiveNative'
self.assertIsNot(v[0].attr[1], v)
buf = self.archiverClass.archivedDataWithRootObject_(d)
self.assertIsInstance(buf, NSData)
v = self.unarchiverClass.unarchiveObjectWithData_(buf)
if self.isKeyed:
self.assertIs(v[1][0].attr, v)
else:
# See 'TestArchiveNative'
self.assertIsNot(v[1][0].attr, v)
示例11: test_methods
def test_methods(self):
## class X(Structure):
## _fields_ = []
self.assertIn("in_dll", dir(type(Structure)))
self.assertIn("from_address", dir(type(Structure)))
self.assertIn("in_dll", dir(type(Structure)))
示例12: toXML
def toXML(self,name=None):
""" Method that creates the XML document for the instance of python class.
Return a string with the xml document.
"""
nameroot = None
if name == None:
nameroot = self.__class__.__name__
else:
nameroot = name
xml = '<%s>'%nameroot
default_attr = dir(type('default',(object,),{}))
for key in dir(self):
if default_attr.count(key) > 0:
continue
element = findElementFromDict(self.__dict__,key)
if element == None:
continue
if isinstance(element,list):
for e in element:
if isinstance(e,ComplexType):
xml += e.toXML(name=key)
else:
xml += '<%s>%s</%s>'%(key,e,key)
elif isinstance(element,Property):
xml += '<%s>%s</%s>'%(key,element.value,key)
elif isinstance(element,ComplexType):
xml += element.toXML(name=key)
else:
xml += '<%s>%s</%s>'%(key,convert(type(element).__name__,element),key)
xml += '</%s>'%nameroot
return str(xml)
示例13: __init__
def __init__(self):
self.db = Database() # classe database
self.i2c = 0
self.getBusValue() # Setta il corretto device
self.A = {}
self.P = {}
self.mBoard = [] # matrive board
self.mBoard_io = [] # matrice IO
self.mProg = [] # matrice programma
self.area_id = ()
self.dir_root = os.path.dirname(os.path.abspath(__file__))
self.initialize()
"""
Example pigpio port
"""
self.pi = pigpio.pi("localhost", 8888) # Instance host, port
print dir(self.pi)
print
self.pi.write(16, False)
print self.pi.read(16) # Read status if IO 16
self.pi.write(16, True) # Write 1 to IO 16
print self.pi.read(16)
for n in range(32): # print mode of GPIO: 0 = INPUT 1 = OUTPUT, 2 = ALT5, 3 = ALT4, 4 = ALT0, 5 = ALT1, 6 = ALT2, 7 = ALT3
print "GPIO n:%s, mode: %s" %(n, self.pi.get_mode(n))
示例14: update
def update(self, new_mac, packet, packet_in):
srcaddr = EthAddr(packet.src)
dstaddr = EthAddr(packet.dst)
log.debug("---------------------------------")
log.debug(srcaddr)
log.debug(dstaddr)
log.debug("MAC Address Store")
log.debug(self.macStore)
log.debug("Done")
log.debug("---------------------------------")
fm = of.ofp_flow_mod(command=of.OFPFC_MODIFY)
fm.match = of.ofp_match.from_packet(packet)
#fm.match.in_port = packet_in.in_port
#fm.match.dl_dst = new_mac
fm.actions.append(of.ofp_action_output(port = self.macStore[new_mac]))
print "dicic"
print dir(fm)
#fm.idle_timeout = 10
#fm.hard_timeout = 30
log.debug("UPDATING FLOWTABLE ENTRY")
self.connection.send(fm)
# We wont loose this package, so we forward it
# to its destination
self.send_packet(packet_in.buffer_id, packet_in.data, self.macStore[new_mac], packet_in.in_port)
self.send_packet(packet_in.buffer_id, packet_in.data, self.macStore[new_mac], packet_in.in_port)
log.debug("-------------Package <"+str(packet_in.buffer_id)+"> forwarded by controller over Port "+str(self.macStore[new_mac]))
示例15: test_usage
def test_usage(self):
gen = (i for i in range(3))
lazy_list = lazyutils.LazyKit(lambda: list(gen))
self.assertEqual(next(gen), 0)
self.assertEqual(lazy_list[1], 1) # pylint: disable=unsubscriptable-object
self.assertEqual(lazy_list[2], 2) # pylint: disable=unsubscriptable-object
self.assertSetEqual(set(dir([])) - set(dir(lazy_list)), set())