本文整理汇总了Python中os.popen方法的典型用法代码示例。如果您正苦于以下问题:Python os.popen方法的具体用法?Python os.popen怎么用?Python os.popen使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.popen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read_process
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def read_process(cmd, args=''):
fullcmd = '%s %s' % (cmd, args)
pipeout = popen(fullcmd)
try:
firstline = pipeout.readline()
cmd_not_found = re.search(
b'(not recognized|No such file|not found)',
firstline,
re.IGNORECASE
)
if cmd_not_found:
raise IOError('%s must be on your system path.' % cmd)
output = firstline + pipeout.read()
finally:
pipeout.close()
return output
示例2: get_gs_file_list
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def get_gs_file_list(path):
if not path.startswith('gs://'):
path = edxbigquery_config.GS_BUCKET + path
print "Getting file list from %s" % path
fnset = OrderedDict()
for dat in os.popen('gsutil ls -l ' + path).readlines():
if dat.strip().startswith('TOTAL'):
continue
try:
x = dat.strip().split()
if len(x)==1:
continue
(size, date, name) = x
except Exception as err:
print "oops, err=%s, dat=%s" % (str(err), dat)
raise
date = dateutil.parser.parse(date)
size = int(size)
fnb = os.path.basename(name)
fnset[fnb] = {'size': size, 'date': date, 'name': name, 'basename': fnb}
return fnset
示例3: write_bars_to_file
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def write_bars_to_file(bars, filename, tz):
"""Creates CSV file from list of Bar instances"""
date_format_str = "%Y%m%d %H%M%S"
rows = [{'DateTime': bar.datetime.astimezone(tz).strftime(date_format_str),
'Open': bar.open,
'High': bar.high,
'Low': bar.low,
'Close': bar.close,
'Volume': bar.volume,
} for bar in bars]
if os.path.exists(filename):
raise Exception("File already exists!")
fd = os.popen("gzip > %s" % filename, 'w') if filename.endswith('.gz') else open(filename, 'w')
with fd:
csv_writer = csv.DictWriter(fd, ['DateTime', 'Open', 'High', 'Low', 'Close', 'Volume'])
csv_writer.writeheader()
csv_writer.writerows(rows)
示例4: write_config
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def write_config(root=None):
if root and os.name == 'nt':
root = root.replace('\\', '/') # For Windows
if root and platform.system().startswith('CYGWIN'): # For cygwin
if root.startswith('/usr/lib'):
cygwin_root = os.popen('cygpath -w /').read().strip().replace('\\', '/')
root = cygwin_root + root[len('/usr'):]
elif STATIC_ROOT.startswith('/cygdrive'):
driver = STATIC_ROOT.split('/')
cygwin_driver = '/'.join(driver[:3])
win_driver = driver[2].upper() + ':'
root = root.replace(cygwin_driver, win_driver)
content = []
with open_(PATH_CONFIG, encoding='utf-8') as f:
for line in f:
if root:
if line.startswith('root'):
line = 'root={}{}'.format(root, os.linesep)
content.append(line)
with open_(PATH_CONFIG, 'w', encoding='utf-8') as f:
f.writelines(content)
示例5: popen
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def popen(cmd, mode="r", buffering=-1):
if not isinstance(cmd, str):
raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
if mode not in ("r", "w"):
raise ValueError("invalid mode %r" % mode)
if buffering == 0 or buffering is None:
raise ValueError("popen() does not support unbuffered streams")
import subprocess, io
if mode == "r":
proc = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
bufsize=buffering)
return _wrap_close(io.TextIOWrapper(proc.stdout), proc)
else:
proc = subprocess.Popen(cmd,
shell=True,
stdin=subprocess.PIPE,
bufsize=buffering)
return _wrap_close(io.TextIOWrapper(proc.stdin), proc)
# Helper for popen() -- a proxy for a file whose close waits for the process
示例6: check_dependencies
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def check_dependencies():
ettercap = popen('which ettercap').read().split("\n")
dhcpd = popen('which dhcpd').read().split("\n")
lista = [dhcpd[0],'/usr/sbin/airbase-ng',
ettercap[0]]
m = []
for i in lista:
m.append(path.isfile(i))
for k,g in enumerate(m):
if m[k] == False:
if k == 0:
print '[%s✘%s] DHCP not %sfound%s.'%(RED,ENDC,YELLOW,ENDC)
for c in m:
if c == False:
exit(1)
break
示例7: get_ip_local
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def get_ip_local(card):
if not card != None:
get_interface = Refactor.get_interfaces()['activated']
out = popen("ifconfig %s | grep 'Bcast'"%(get_interface)).read().split()
for i in out:
if search("end",i):
if len(out) > 0:
ip = out[2].split(":")
return ip[0]
if len(out) > 0:
ip = out[1].split(":")
return ip[1]
else:
out = popen("ifconfig %s | grep 'Bcast'"%(card)).read().split()
for i in out:
if search("end",i):
if len(out) > 0:
ip = out[2].split(":")
return ip[0]
if len(out) > 0:
ip = out[1].split(":")
return ip[1]
return None
示例8: conf_attack
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def conf_attack(self,bool_conf):
if bool_conf:
self.ip = self.txt_redirect.text()
if len(self.ip) != 0:
iptables = [
'iptables -t nat --flush',
'iptables --zero',
'echo 1 > /proc/sys/net/ipv4/ip_forward',
'iptables -A FORWARD --in-interface '+self.interfaces['gateway']+' -j ACCEPT',
'iptables -t nat --append POSTROUTING --out-interface ' +self.interfaces['activated'] +' -j MASQUERADE',
'iptables -t nat -A PREROUTING -p tcp --dport 80 --jump DNAT --to-destination '+self.ip
]
for i in iptables:
try:system(i)
except:pass
else:
QMessageBox.information(self,'Error Redirect IP','Redirect IP not found')
else:
nano = [
'echo 0 > /proc/sys/net/ipv4/ip_forward','iptables --flush',
'iptables --table nat --flush' ,\
'iptables --delete-chain', 'iptables --table nat --delete-chain'
]
for delete in nano: popen(delete)
示例9: run
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def run(self, edit):
selectedcode = ""
sels = self.view.sel()
for sel in sels:
selectedcode = selectedcode + self.view.substr(sel)
if len(selectedcode) == 0:
selectedcode = self.view.substr(self.view.line(sel))
selectedcode = selectedcode + "\n"
dofile_path =tempfile.gettempdir()+'selectedlines_piupiu.do'
with codecs.open(dofile_path, 'w', encoding='utf-8') as out:
out.write(selectedcode)
# cmd = "/Applications/Stata/StataSE.app/Contents/MacOS/StataSE 'do /Users/piupiu/Downloads/a'"
# os.popen(cmd)
# cmd = """osascript -e 'tell application "StataSE" to open POSIX file "{0}"' -e 'tell application "{1}" to activate' &""".format(dofile_path, "Viewer")
# os.system(cmd)
version, stata_app_id = get_stata_version()
cmd = """osascript<< END
tell application id "{0}"
DoCommandAsync "do {1}" with addToReview
end tell
END""".format(stata_app_id,dofile_path)
print(cmd)
print("stata_app_id")
print(stata_app_id)
os.system(cmd)
示例10: image_to_display
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def image_to_display(std_scr, path, login_win_row=0, start=None, length=None):
"""
Display an image
"""
login_max_y, login_max_x = std_scr.getmaxyx()
rows, columns = os.popen('stty size', 'r').read().split()
if not start:
start = 2
if not length:
length = int(columns) - 2 * start
i = Image.open(path)
i = i.convert('RGBA')
w, h = i.size
i.load()
width = min(w, length, login_max_x-1)
height = int(float(h) * (float(width) / float(w)))
height //= 2
i = i.resize((width, height), Image.ANTIALIAS)
height = min(height, 90, login_max_y-1)
for y in xrange(height):
for x in xrange(width):
p = i.getpixel((x, y))
r, g, b = p[:3]
pixel_print(std_scr, login_win_row+y, start+x, rgb2short(r, g, b))
示例11: docker_image_clean
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def docker_image_clean(image_name):
# Remove all excess whitespaces on edges, split on spaces and grab the first word.
# Wraps in double quotes so bash cannot interpret as an exec
image_name = '"{}"'.format(image_name.strip().split(' ')[0])
# Regex acts as a whitelist here. Only alphanumerics and the following symbols are allowed: / . : -.
# If any not allowed are found, replaced with second argument to sub.
image_name = re.sub('[^0-9a-zA-Z/.:-]+', '', image_name)
return image_name
# def docker_get_size():
# return os.popen("docker system df | awk -v x=4 'FNR == 2 {print $x}'").read().strip()
#
#
# def docker_prune():
# """Runs a prune on docker if our images take up more than what's defined in settings."""
# # May also use docker system df --format "{{.Size}}"
# image_size = docker_get_size()
# image_size_measurement = image_size[-2:]
# image_size = float(image_size[:-2])
#
# if image_size > settings.DOCKER_MAX_SIZE_GB and image_size_measurement == "GB":
# logger.info("Pruning")
# os.system("docker system prune --force")
示例12: ticket
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def ticket(self):
file_name = 'tickets/' + str(self.data[KEYS.CARID]) + '.txt'
with open(file_name, 'w') as file:
lic_num = str(self.license_number_lineedit.text())
rule = self.data[KEYS.RULENAME]
fine = str(self.data[KEYS.RULEFINE])
file.write('########################################\n')
file.write('# License Number #\n')
file.write('#' + ''.join([' ' for i in range(35 - len(lic_num))]) + lic_num + ' #\n')
file.write('# Rule Broken : #\n')
file.write('#'+''.join([' ' for i in range(35 - len(rule))]) + rule + ' #\n')
file.write('# Fine : #\n')
file.write('#'+''.join([' ' for i in range(35 - len(fine))]) + fine + ' #\n')
file.write('########################################\n')
self.destroy()
os.popen("kate " + file_name)
示例13: init_params
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def init_params(net):
'''Init layer parameters.'''
for m in net.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal(m.weight, mode='fan_out')
if m.bias:
init.constant(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
init.constant(m.weight, 1)
init.constant(m.bias, 0)
elif isinstance(m, nn.Linear):
init.normal(m.weight, std=1e-3)
if m.bias:
init.constant(m.bias, 0)
#_, term_width = os.popen('stty size', 'r').read().split()
# term_width = int(term_width)
示例14: is_running
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def is_running(program):
'''
Returns True if at least one instance of program name is running.
program will search through the command line, so asking for
"connect" will return True for the process
"wpa_supplicant -c/etc/connect.conf"
'''
# Search using a regex, to exclude itself (pgrep) from the list
cmd = "pgrep -fc '[{}]{}'".format(program[0], program[1:])
running = 0
try:
result = os.popen(cmd)
running = int(result.read().strip())
except Exception:
pass
return running > 0
示例15: check
# 需要导入模块: import os [as 别名]
# 或者: from os import popen [as 别名]
def check(module):
global passed, failed
'''
apply pylint to the file specified if it is a *.py file
'''
module_name = module.rsplit('/', 1)[1]
if module[-3:] == ".py" and module_name not in IGNORED_FILES:
print "CHECKING ", module
pout = os.popen('pylint %s'% module, 'r')
for line in pout:
if "Your code has been rated at" in line:
print "PASSED pylint inspection: " + line
passed += 1
return True
if "-error" in line:
print "FAILED pylint inspection: " + line
failed += 1
errors.append("FILE: " + module)
errors.append("FAILED pylint inspection: " + line)
return False