本文整理汇总了Python中os.readlink方法的典型用法代码示例。如果您正苦于以下问题:Python os.readlink方法的具体用法?Python os.readlink怎么用?Python os.readlink使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.readlink方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: netstat_tcp6
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def netstat_tcp6():
'''
This function returns a list of tcp connections utilizing ipv6. Please note that in order to return the pid of of a
network process running on the system, this script must be ran as root.
'''
tcpcontent = _tcp6load()
tcpresult = []
for line in tcpcontent:
line_array = _remove_empty(line.split(' '))
l_host, l_port = _convert_ipv6_port(line_array[1])
r_host, r_port = _convert_ipv6_port(line_array[2])
tcp_id = line_array[0]
state = TCP_STATE[line_array[3]]
uid = pwd.getpwuid(int(line_array[7]))[0]
inode = line_array[9]
pid = _get_pid_of_inode(inode)
try: # try read the process name.
exe = os.readlink('/proc/' + pid + '/exe')
except:
exe = None
nline = [tcp_id, uid, l_host + ':' + l_port,
r_host + ':' + r_port, state, pid, exe]
tcpresult.append(nline)
return tcpresult
示例2: syncToRemote
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def syncToRemote(self, p, spec):
if not self.writeStore:
return
tarballNameWithRev = format("%(package)s-%(version)s-%(revision)s.%(architecture)s.tar.gz",
architecture=self.architecture,
**spec)
cmd = format("cd %(workdir)s && "
"TARSHA256=`sha256sum %(storePath)s/%(tarballNameWithRev)s | awk '{ print $1 }'` && "
"s3cmd put -s -v --host s3.cern.ch --add-header \"x-amz-meta-sha256:$TARSHA256\" --host-bucket %(b)s.s3.cern.ch %(storePath)s/%(tarballNameWithRev)s s3://%(b)s/%(storePath)s/ 2>/dev/null || true\n"
"HASHEDURL=`readlink %(linksPath)s/%(tarballNameWithRev)s | sed -e's|^../../||'` &&"
"echo $HASHEDURL | s3cmd put -s -v --host s3.cern.ch --host-bucket %(b)s.s3.cern.ch --add-header=\"x-amz-website-redirect-location:https://s3.cern.ch/swift/v1/%(b)s/TARS/${HASHEDURL}\" - s3://%(b)s/%(linksPath)s/%(tarballNameWithRev)s 2>/dev/null || true\n",
workdir=self.workdir,
b=self.remoteStore,
storePath=spec["storePath"],
linksPath=spec["linksPath"],
tarballNameWithRev=tarballNameWithRev)
err = execute(cmd)
dieOnError(err, "Unable to upload tarball.")
# Creates a directory in the store which contains symlinks to the package
# and its direct / indirect dependencies
示例3: get_function_by_ifname
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def get_function_by_ifname(ifname):
"""Get the function by the interface name
Given the device name, returns the PCI address of a device
and returns True if the address is in a physical function.
"""
dev_path = "/sys/class/net/%s/device" % ifname
sriov_totalvfs = 0
if os.path.isdir(dev_path):
try:
# sriov_totalvfs contains the maximum possible VFs for this PF
with open(os.path.join(dev_path, _SRIOV_TOTALVFS)) as fd:
sriov_totalvfs = int(fd.read())
return (os.readlink(dev_path).strip("./"),
sriov_totalvfs > 0)
except (IOError, ValueError):
return os.readlink(dev_path).strip("./"), False
return None, False
示例4: get_vf_num_by_pci_address
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def get_vf_num_by_pci_address(pci_addr):
"""Get the VF number based on a VF's pci address
A VF is associated with an VF number, which ip link command uses to
configure it. This number can be obtained from the PCI device filesystem.
"""
VIRTFN_RE = re.compile(r"virtfn(\d+)")
virtfns_path = "/sys/bus/pci/devices/%s/physfn/virtfn*" % (pci_addr)
vf_num = None
try:
for vf_path in glob.iglob(virtfns_path):
if re.search(pci_addr, os.readlink(vf_path)):
t = VIRTFN_RE.search(vf_path)
vf_num = t.group(1)
break
except Exception:
pass
if vf_num is None:
raise exception.PciDeviceNotFoundById(id=pci_addr)
return vf_num
示例5: extract
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def extract(
self, identifier: str, matched_fname: str, current_meta: Metadata
) -> Metadata:
try:
target = os.readlink(self.path + "{}/binary".format(identifier))
except OSError:
return {}
binary_hash = target.split("/")[-1]
obj = {
"cuckoo_hash": {"value": binary_hash},
"cuckoo_analysis": {
"display_text": "cuckoo:{}".format(identifier),
"value": identifier,
},
}
return obj
示例6: list
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def list():
_dir = get_dir(request.url_root)
fn = os.path.join(_dir, 'current')
current = None
if os.path.exists(fn):
current = os.readlink(fn)
ret = ''
for i in sorted(os.listdir(_dir), reverse=True):
if not digits_re.match(i):
continue
ret = ret + '<a href="diff/%s">%s</a>' % (i, i)
if i == current:
ret = ret + " <--"
ret = ret + '<br/>'
return ret
示例7: current
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def current():
_dir = get_dir(request.url_root)
fn = os.path.join(_dir, 'current')
if request.method == 'POST':
if not 'version' in request.form:
return "missing version", 400
version = request.form['version']
if not digits_re.match(version):
return "malformed version", 400
if not os.path.exists(os.path.join(_dir, version)):
return "invalid version", 400
tmpfn = os.path.join(_dir, '.' + version)
app.logger.debug(tmpfn)
if os.path.exists(tmpfn):
os.unlink(tmpfn)
os.symlink(version, tmpfn)
os.rename(tmpfn, fn)
return "ok"
else:
if not os.path.exists(fn):
return "", 404
return os.readlink(fn)
示例8: main
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def main():
with tarfile.open(os.path.join(settings.PRODUCTS_ROOT, 'ctw-annotations.tar.gz'), 'w|gz') as tar:
tar.add(settings.DATA_LIST, filter=reset)
tar.add(settings.TRAIN, filter=reset)
tar.add(settings.VAL, filter=reset)
tar.add(settings.TEST_CLASSIFICATION, filter=reset)
with open(settings.DATA_LIST) as f:
data_list = json.load(f)
all = (('trainval', data_list['train'] + data_list['val'], settings.TRAINVAL_IMAGE_DIR),
('test', data_list['test_cls'] + data_list['test_det'], settings.TEST_IMAGE_DIR))
for prefix, meta, src_dir in all:
meta.sort(key=operator.itemgetter('image_id'))
delta = 1000
n = len(range(0, len(meta), delta))
for i in range(0, len(meta), delta):
submeta = meta[i:i + delta]
with tarfile.open(os.path.join(settings.PRODUCTS_ROOT, 'ctw-{}-{:02d}-of-{:02d}.tar'.format(prefix, i // delta + 1, n)), 'w') as tar:
for o in submeta:
tar.add(os.readlink(os.path.join(src_dir, o['file_name'])), filter=reset)
示例9: _bind_device
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def _bind_device(self, pci, driver, old_driver=None):
if not old_driver:
old_driver_path = '/sys/bus/pci/devices/{}/driver'.format(pci)
old_driver_link = os.readlink(old_driver_path)
old_driver = os.path.basename(old_driver_link)
if old_driver not in constants.MELLANOX_DRIVERS:
unbind_path = '/sys/bus/pci/drivers/{}/unbind'.format(old_driver)
bind_path = '/sys/bus/pci/drivers/{}/bind'.format(driver)
with open(unbind_path, 'w') as unbind_fd:
unbind_fd.write(pci)
override = "/sys/bus/pci/devices/{}/driver_override".format(pci)
with open(override, 'w') as override_fd:
override_fd.write("\00")
with open(override, 'w') as override_fd:
override_fd.write(driver)
with open(bind_path, 'w') as bind_fd:
bind_fd.write(pci)
LOG.info("Device %s was binded on driver %s. Old driver is %s",
pci, driver, old_driver)
return old_driver
示例10: _get_pci_info
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def _get_pci_info(self, pf, vf_index):
pci_slot = ''
pci_vendor_info = ''
vendor_path = '/sys/class/net/{}/device/virtfn{}/vendor'.format(
pf, vf_index)
with open(vendor_path) as vendor_file:
vendor_full = vendor_file.read()
vendor = vendor_full.split('x')[1].strip()
device_path = '/sys/class/net/{}/device/virtfn{}/device'.format(
pf, vf_index)
with open(device_path) as device_file:
device_full = device_file.read()
device = device_full.split('x')[1].strip()
pci_vendor_info = '{}:{}'.format(vendor, device)
vf_path = '/sys/class/net/{}/device/virtfn{}'.format(
pf, vf_index)
pci_slot_path = os.readlink(vf_path)
pci_slot = pci_slot_path.split('/')[1]
return {'pci_slot': pci_slot,
'pci_vendor_info': pci_vendor_info}
示例11: resolveLink
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def resolveLink(path):
"""Resolves links and detects loops"""
paths_seen = []
while islink(path):
if path in paths_seen:
# Already seen this path, so we must have a symlink loop
return path, True
paths_seen.append(path)
# Resolve where the link points to
resolved = os.readlink(path)
if not isabs(resolved):
dir_name = dirname(path)
path = normpath(dir_name + sep + resolved)
else:
path = normpath(resolved)
return path, False
示例12: updateStatus
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def updateStatus(self):
"""Updates internal fields"""
if os.path.exists(self._dirName):
self.icon = getIcon('dirclosed.png')
self.populated = False
self.lazyPopulation = True
if os.path.islink(self._dirName):
self.isLink = True
linkTo = os.readlink(self._dirName)
realpath = os.path.realpath(self._dirName)
self.toolTip = "-> " + linkTo + " (" + realpath + ")"
self.icon = getIcon('dirlink.png')
else:
self.icon = getIcon('dirbroken.png')
self.populated = True
self.lazyPopulation = False
self.childItems = []
self.childItemsSize = 0
示例13: info
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def info(self, path, **kwargs):
path = self._strip_protocol(path)
out = os.stat(path, follow_symlinks=False)
dest = False
if os.path.islink(path):
t = "link"
dest = os.readlink(path)
elif os.path.isdir(path):
t = "directory"
elif os.path.isfile(path):
t = "file"
else:
t = "other"
result = {"name": path, "size": out.st_size, "type": t, "created": out.st_ctime}
for field in ["mode", "uid", "gid", "mtime"]:
result[field] = getattr(out, "st_" + field)
if dest:
result["destination"] = dest
try:
out2 = os.stat(path, follow_symlinks=True)
result["size"] = out2.st_size
except IOError:
result["size"] = 0
return result
示例14: create_symlinks
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def create_symlinks(venv=VENV, atlas_clients=False):
print 'Installing binaries symlinks ...'
bin_dir = os.path.join(ROOT, "bin")
venv_bin_dir = os.path.join(venv, "bin")
binaries = os.listdir(bin_dir)
for binary in binaries:
source = os.path.join(bin_dir, binary)
link_name = os.path.join(venv_bin_dir, binary)
try:
os.path.exists(link_name) and source != os.readlink(link_name)
except OSError, e:
if e.errno == errno.EINVAL:
print 'Delete broken symlink: %(link_name)s -> %(source)s' % locals()
os.remove(link_name)
else:
raise e
if not os.path.exists(link_name):
print 'Create the symlink: %(link_name)s -> %(source)s' % locals()
os.symlink(source, link_name)
示例15: kill_stdout_reader
# 需要导入模块: import os [as 别名]
# 或者: from os import readlink [as 别名]
def kill_stdout_reader():
""" Kill whatever is on the otherside of stdout """
std_out_fd = '/proc/{pid}/fd/{stdout}'.format(pid=os.getpid(),
stdout=STDOUT)
readlink = os.readlink(std_out_fd)
pipe_node = re.match('pipe:\[([0-9]+)]', readlink).groups()[0]
cmd = ("lsof | "
"awk '{{if($4 == \"{stdin}r\" && $8 == {pipe_node}) print $2}}'"
"".format(stdin=str(STDIN),
pipe_node=pipe_node))
lsof = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE)
lsof.wait()
stdout_reader_pid = int(lsof.stdout.read())
try:
os.kill(stdout_reader_pid, 9)
except:
pass
# Nothing really to be done here, it is probalby hopeless to try
# to do anything more.