【发布时间】:2011-08-09 19:17:36
【问题描述】:
我对 python 还是很陌生,但是我需要与一些编写为一堆 python 模块的软件(.py 文件,以防我错误地将它们识别为“模块”。)这个程序有一些非常有用的以及我真的无法破解的复杂功能(如果没有别的,因为每次更新软件时,我都必须重新破解所有内容。)
我有一个如下所示的 python 脚本:
from software import thingfromsoftware
def mything(x,y,someboolean=True,etc)
var=thingfromsoftware(x,y)
#....code....
setattr(var, 'dimensions', somearraything)
return(var)
那么,如果我尝试:
result=mything(4,5)
那么result 正确地包含了首先通过thingfromsoftware 分配给它的所有属性的值,但尚未分配result.dimensions (has no attribute "dimensions")
目标是以某种半连贯的方式存储由myfunctionthing 计算和配置的每个result 的dimensions。
真实代码(根据要求)
from ase.structure import nanotube
from ase import Atoms, view, io
from numpy import *
from Avogadro import Molecule, MoleculeFile
import cPickle as pickle
import os
def make_nanotube(n,m,length=1,TYPE='free'):
#This will set up leads so transport occures along the z axis and leads are aligned along the y axis (so they may be separated along the x axis.)
os.chdir("/tmp")
print 'Making ('+str(n)+','+str(m)+') nanotube with '+str(length)+" unit cell as "+str(TYPE)
tube = nanotube(n, m, length=length, bond=1.420, symbol='C')
center=tube.get_center_of_mass()
name='tube:('+str(n)+', '+str(m)+'):unit cells:'+str(length)+':'+str(TYPE)+'.xyz'
io.write(str(name), tube)
print 'Computing bonds'
mol = MoleculeFile.readMolecule(str(name))
RELOAD=0
for atom in mol.atoms[:]:
if len(atom.bonds)<2 and atom.pos[-1]<center[-1]:
print 'Relocating atom '+str(atom.index)+' from '+str(atom.pos[-1])+' to '+str(tube.get_cell()[-1, -1] + atom.pos[-1])
tube.positions[atom.index, -1] += tube.get_cell()[-1, -1]
RELOAD=1
print 'Orienting tube'
tip_atom=tube.get_positions()[:, -1].argmax() #the tip on the right (farther) end
tip=tube.get_positions()[tip_atom]
tube.rotate(append(tip[:-1], 0), append(center[0], zeros(2)), center=center) #rotate so that the tip is slanted toward x-axis (center[0],0,0)
tube.center()
setattr(tube, 'dimensions', [tube.get_cell()[0, 0]/2,tube.get_cell()[-1,-1]])
cell=tube.get_cell()
if TYPE!='bare':
if RELOAD==1:
print 'Recomputing bonds'
io.write(str(name), tube)
mol = MoleculeFile.readMolecule(str(name))
print 'Adding hydrogens'
mol.addHydrogens()
if TYPE=='left lead':
print 'Removing hydrogens from the right side'
for atom in mol.atoms[:]:
if atom.pos[2]<center[2]:
mol.removeHydrogens(atom)
elif TYPE=='right lead':
print 'Removing hydrogens from the left side'
for atom in mol.atoms[:]:
if atom.pos[2]>center[2]:
mol.removeHydrogens(atom)
MoleculeFile.writeMolecule(mol,str(name))
tube=io.read(str(name))
else:
tube.set_cell(cell)
return(tube)
【问题讨论】:
-
您发布的代码似乎没有任何问题。您需要向我们展示真实的代码。
-
好的,我刚做了。它相当长。这就是我一开始没有发布它的原因。
-
@agf 我在 python 交互式会话中运行它: execfile('/home/labgroup/Documents/scripts/make_nanotube.py');测试=make_nanotube(4,4); test.dimensions;