Python os.popen() Examples

The following are 30 code examples of os.popen(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: tools.py    From iqfeed with Apache License 2.0 7 votes vote down vote up
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) 
Example #2
Source File: utils.py    From 3vilTwinAttacker with MIT License 6 votes vote down vote up
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 
Example #3
Source File: blue_eye.py    From blue_eye with GNU General Public License v3.0 6 votes vote down vote up
def header():
    try:
        print("\033[34mScanning.... HTTP Header \033[0m" + target)
        time.sleep(1.5)
        command = ("http -v " + target)
        proces = os.popen(command)
        results = str(proces.read())
        print("\033[1;34m" + results + command + "\033[1;m")
        print ("»"*60 + "\n")

    except Exception:
        pass

    except KeyboardInterrupt:
            print("\n")
            print("[-] User Interruption Detected..!")
            time.sleep(1) 
Example #4
Source File: __init__.py    From pyhanlp with Apache License 2.0 6 votes vote down vote up
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) 
Example #5
Source File: _cpmodpy.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #6
Source File: pylint-recursive.py    From PokemonGo-Bot with MIT License 6 votes vote down vote up
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 
Example #7
Source File: processes.py    From kano-toolset with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #8
Source File: _cpmodpy.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def popen(fullcmd):
        p = subprocess.Popen(fullcmd, shell=True,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                             close_fds=True)
        return p.stdout 
Example #9
Source File: os.py    From jawfish with MIT License 6 votes vote down vote up
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 
Example #10
Source File: utils.py    From mixup_pytorch with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: gsutil.py    From edx2bigquery with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #12
Source File: DetailLogWindow.py    From Traffic-Rules-Violation-Detection with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #13
Source File: worker.py    From ctw-baseline with MIT License 6 votes vote down vote up
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") 
Example #14
Source File: c_image.py    From baidufm-py with MIT License 6 votes vote down vote up
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)) 
Example #15
Source File: StataImproved.py    From StataImproved with MIT License 6 votes vote down vote up
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) 
Example #16
Source File: check.py    From 3vilTwinAttacker with MIT License 6 votes vote down vote up
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 
Example #17
Source File: ModuleArpPosion.py    From 3vilTwinAttacker with MIT License 6 votes vote down vote up
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) 
Example #18
Source File: xbundle.py    From edx2bigquery with GNU General Public License v2.0 5 votes vote down vote up
def pp_xml(self,xml):
        os.popen('xmllint --format -o tmp.xml -','w').write(etree.tostring(xml))
        return open('tmp.xml').read() 
Example #19
Source File: validate.py    From cloudify-manager-blueprints with Apache License 2.0 5 votes vote down vote up
def _validate_openssl_version(required_version):
    ctx.logger.info('Validating OpenSSL version...')
    try:
        # we can't just `import ssl` and check the version
        # because sometimes python is referencing to the old ssl version
        output = os.popen('openssl version').read()
        version = output.split()[1]
        if LooseVersion(version) < LooseVersion(required_version):
            msg = "Cloudify Manager requires OpenSSL {0}, " \
                  "current version: {1}".format(required_version, version)
            ctx.logger.warn('Validating Warning: {0}'.format(msg))
    except Exception as ex:
        return _error(
            "Cloudify Manager requires OpenSSL {0}, Error: {1}"
            "".format(required_version, ex)) 
Example #20
Source File: Plot.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def terminal_size():
    try:
        row, col = os.popen('stty size', 'r').read().split()
    except:
        # Use defaults
        row, col = "100", "100",
    return row, col 
Example #21
Source File: PipelineStep_identifyBadAntennas.py    From prefactor with GNU General Public License v3.0 5 votes vote down vote up
def find_flagged_antennas(ms_file):
    
   print('Reading ' + str(ms_file))
   outputs = os.popen('DPPP msin=' + ms_file + ' msout=. steps=[count] count.type=counter count.warnperc=100 | grep NOTE').readlines()
   flaggedants = [ output.split('(')[-1].rstrip(')\n') for output in outputs if 'station' in output ]
   return(flaggedants) 
Example #22
Source File: concat_MS_CWL.py    From prefactor with GNU General Public License v3.0 5 votes vote down vote up
def getfilesize(MS):
   
   size = int(os.popen('du -cks ' + MS).readlines()[0].split()[0])
   return size

   pass

######################################################################## 
Example #23
Source File: concat_MS_CWL.py    From prefactor with GNU General Public License v3.0 5 votes vote down vote up
def getsystemmemory():
   
   memory = int(os.popen('cat /proc/meminfo | grep MemAvailable').readlines()[0].split(':')[-1].split()[0])
   return memory
   pass

######################################################################## 
Example #24
Source File: concat_MS.py    From prefactor with GNU General Public License v3.0 5 votes vote down vote up
def getfilesize(MS):
   
   size = int(os.popen('du -cks ' + MS).readlines()[0].split()[0])
   return size

   pass

######################################################################## 
Example #25
Source File: concat_MS.py    From prefactor with GNU General Public License v3.0 5 votes vote down vote up
def getsystemmemory():
   
   memory = int(os.popen('cat /proc/meminfo | grep MemAvailable').readlines()[0].split(':')[-1].split()[0])
   return memory
   pass

######################################################################## 
Example #26
Source File: tty.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def size():
    """Determines the height and width of the console window

        Returns:
            tuple of int: The height in lines, then width in characters
    """
    try:
        assert os != 'nt' and sys.stdout.isatty()
        rows, columns = os.popen('stty size', 'r').read().split()
    except (AssertionError, AttributeError, ValueError):
        # in case of failure, use dimensions of a full screen 13" laptop
        rows, columns = DEFAULT_HEIGHT, DEFAULT_WIDTH

    return int(rows), int(columns) 
Example #27
Source File: make_summary.py    From prefactor with GNU General Public License v3.0 5 votes vote down vote up
def find_flagged_fraction(ms_file):
    
   outputs  = os.popen('DPPP msin=' + ms_file + ' msout=. steps=[count] count.type=counter count.warnperc=0.0000001 | grep NOTE').readlines()
   fraction_flagged = { output.split('(')[-1].rstrip(')\n'):output.split('%')[0][-5:].strip() for output in outputs if 'station' in output }
   return(fraction_flagged)

############################################################################### 
Example #28
Source File: ModuleDnsSpoof.py    From 3vilTwinAttacker with MIT License 5 votes vote down vote up
def Start_Attack(self):
        self.targets = {}
        if (len(self.txt_target.text()) and  len(self.txt_gateway.text())) == 0:
            QMessageBox.information(self, 'Error Arp Attacker', 'you need set the input correctly')
        else:
            if (len(self.txt_target.text()) and len(self.txt_gateway.text())) and len(self.txt_redirect.text()) != 0:
                if len(self.txt_redirect.text()) != 0:
                    self.domains = []
                    for index in xrange(self.myListDns.count()):
                        self.domains.append(str(self.myListDns.item(index).text()))
                    for i in self.domains:
                        self.targets[i.split(':')[0]] = (i.split(':')[1]).replace('\n','')
                    self.domains = []
                    popen('echo 1 > /proc/sys/net/ipv4/ip_forward')
                    arp_target = ThARP_posion(str(self.txt_gateway.text()),str(self.txt_target.text()))
                    arp_target.setName('Arp Posion:: [target]')
                    arp_target.setDaemon(True)
                    threadloading['arps'].append(arp_target)
                    arp_target.start()

                    arp_gateway = ThARP_posion(str(self.txt_target.text()),str(self.txt_gateway.text()))
                    arp_gateway.setName('Arp Posion:: [gateway]')
                    arp_gateway.setDaemon(True)
                    threadloading['arps'].append(arp_gateway)
                    arp_gateway.start()

                    thr = ThDnsSpoofAttack(self.targets,
                    str(self.ComboIface.currentText()),'udp port 53',True,str(self.txt_redirect.text()))
                    thr.redirection()
                    self.connect(thr,SIGNAL('Activated ( QString ) '), self.StopArpAttack)
                    thr.setObjectName('Dns Spoof')
                    self.ThreadDirc['dns_spoof'].append(thr)
                    thr.start()
                    self.StatusMonitor(True,'dns_spoof') 
Example #29
Source File: utils.py    From 3vilTwinAttacker with MIT License 5 votes vote down vote up
def get_mac(host):
        fields = popen('grep "%s " /proc/net/arp' % host).read().split()
        if len(fields) == 6 and fields[3] != "00:00:00:00:00:00":
            return fields[3]
        else:
            return ' not detected' 
Example #30
Source File: AutoSynchroTime.py    From 12306 with MIT License 5 votes vote down vote up
def autoSynchroTime():
    """
    同步北京时间,执行时候,请务必用sudo,sudo,sudo 执行,否则会报权限错误,windows打开ide或者cmd请用管理员身份
    :return:
    """
    c = ntplib.NTPClient()

    hosts = ['ntp1.aliyun.com', 'ntp2.aliyun.com', 'ntp3.aliyun.com', 'ntp4.aliyun.com', 'cn.pool.ntp.org']

    print(u"正在同步时间,请耐心等待30秒左右,如果下面有错误发送,可以忽略!!")
    print(u"系统当前时间{}".format(str(datetime.datetime.now())[:22]))
    system = platform.system()
    if system == "Windows":  # windows 同步时间未测试过,参考地址:https://www.jianshu.com/p/92ec15da6cc3
        for host in hosts:
            os.popen('w32tm /register')
            os.popen('net start w32time')
            os.popen('w32tm /config /manualpeerlist:"{}" /syncfromflags:manual /reliable:yes /update'.format(host))
            os.popen('ping -n 3 127.0.0.1 >nul')
            sin = os.popen('w32tm /resync')
            if sin is 0:
                break
    else:  # mac同步地址,如果ntpdate未安装,brew install ntpdate    linux 安装 yum install -y ntpdate
        for host in hosts:
            sin = os.popen('ntpdate {}'.format(host))
            if sin is 0:
                break
    print(u"同步后时间:{}".format(str(datetime.datetime.now())[:22]))