当前位置: 首页>>代码示例>>Python>>正文


Python os.popen方法代码示例

本文整理汇总了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 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:18,代码来源:_cpmodpy.py

示例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 
开发者ID:mitodl,项目名称:edx2bigquery,代码行数:23,代码来源:gsutil.py

示例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) 
开发者ID:tibkiss,项目名称:iqfeed,代码行数:23,代码来源:tools.py

示例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) 
开发者ID:hankcs,项目名称:pyhanlp,代码行数:23,代码来源:__init__.py

示例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 
开发者ID:war-and-code,项目名称:jawfish,代码行数:24,代码来源:os.py

示例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 
开发者ID:wi-fi-analyzer,项目名称:3vilTwinAttacker,代码行数:18,代码来源:check.py

示例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 
开发者ID:wi-fi-analyzer,项目名称:3vilTwinAttacker,代码行数:25,代码来源:utils.py

示例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) 
开发者ID:wi-fi-analyzer,项目名称:3vilTwinAttacker,代码行数:26,代码来源:ModuleArpPosion.py

示例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) 
开发者ID:zizhongyan,项目名称:StataImproved,代码行数:27,代码来源:StataImproved.py

示例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)) 
开发者ID:tdoly,项目名称:baidufm-py,代码行数:26,代码来源:c_image.py

示例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") 
开发者ID:yuantailing,项目名称:ctw-baseline,代码行数:26,代码来源:worker.py

示例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) 
开发者ID:rahatzamancse,项目名称:Traffic-Rules-Violation-Detection,代码行数:18,代码来源:DetailLogWindow.py

示例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) 
开发者ID:leehomyc,项目名称:mixup_pytorch,代码行数:20,代码来源:utils.py

示例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 
开发者ID:KanoComputing,项目名称:kano-toolset,代码行数:19,代码来源:processes.py

示例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 
开发者ID:PokemonGoF,项目名称:PokemonGo-Bot,代码行数:22,代码来源:pylint-recursive.py


注:本文中的os.popen方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。