Python os.popen() Examples

The following are 30 code examples for showing how to use os.popen(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os , or try the search function .

Example 1
Project: iqfeed   Author: tibkiss   File: tools.py    License: Apache License 2.0 8 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
Project: cherrypy   Author: cherrypy   File: _cpmodpy.py    License: BSD 3-Clause "New" or "Revised" License 7 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 3
Project: pyhanlp   Author: hankcs   File: __init__.py    License: 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 4
Project: jawfish   Author: war-and-code   File: os.py    License: 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 5
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: check.py    License: 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 6
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: utils.py    License: 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 7
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: ModuleArpPosion.py    License: 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 8
Project: StataImproved   Author: zizhongyan   File: StataImproved.py    License: 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 9
Project: baidufm-py   Author: tdoly   File: c_image.py    License: 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 10
Project: ctw-baseline   Author: yuantailing   File: worker.py    License: 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 11
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 12
Project: edx2bigquery   Author: mitodl   File: gsutil.py    License: 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 13
Project: mixup_pytorch   Author: leehomyc   File: utils.py    License: 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 14
Project: kano-toolset   Author: KanoComputing   File: processes.py    License: 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 15
Project: PokemonGo-Bot   Author: PokemonGoF   File: pylint-recursive.py    License: 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 16
Project: blue_eye   Author: BullsEye0   File: blue_eye.py    License: 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 17
Project: blue_eye   Author: BullsEye0   File: blue_eye.py    License: GNU General Public License v3.0 6 votes vote down vote up
def nmaps():
    try:
        print("\033[34mScanning.... Nmap Port Scan: \033[0m" + target)
        print ("[+]\033[34m - --> \033[0mThis may take a moment \033[34mBlue Eye\033[0m gathers the data.....\n")
        time.sleep(1)

        scanner = nmap.PortScanner()
        command = ("nmap -Pn " + target)
        process = os.popen(command)
        results = str(process.read())
        logPath = "logs/nmap-" + strftime("%Y-%m-%d_%H:%M:%S", gmtime())

        print("\033[34m" + results + command + logPath + "\033[0m")
        print("\033[34mNmap Version: \033[0m", scanner.nmap_version())
        print ("»"*60 + "\n")

    except Exception:
        pass

    except KeyboardInterrupt:
            print("\n")
            print("[-] User Interruption Detected..!")
            time.sleep(1) 
Example 18
Project: cherrypy   Author: cherrypy   File: _cpmodpy.py    License: BSD 3-Clause "New" or "Revised" License 5 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 19
Project: cherrypy   Author: cherrypy   File: _cpmodpy.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def popen(fullcmd):
        pipein, pipeout = os.popen4(fullcmd)
        return pipeout 
Example 20
Project: cherrypy   Author: cherrypy   File: _cpmodpy.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def stop(self):
        os.popen('apache -k stop')
        self.ready = False 
Example 21
Project: multibootusb   Author: mbusb   File: gen.py    License: GNU General Public License v2.0 5 votes vote down vote up
def linuxRam(self):
        """
        Returns the RAM of a Linux system
        """
        totalMemory = os.popen("free -m").readlines()[1].split()[1]
        return int(totalMemory) 
Example 22
Project: EvilOSX   Author: cys3c   File: Server.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_csr():
    if not os.path.isfile("server.key"):
        # See https://en.wikipedia.org/wiki/Certificate_signing_request#Procedure
        # Basically we're saying "verify that the request is actually from EvilOSX".
        print MESSAGE_INFO + "Generating certificate signing request to encrypt sockets..."

        information = "/C=US/ST=EvilOSX/L=EvilOSX/O=EvilOSX/CN=EvilOSX"
        os.popen("openssl req -newkey rsa:2048 -nodes -x509 -subj {0} -keyout server.key -out server.crt 2>&1".format(information)) 
Example 23
Project: pywren-ibm-cloud   Author: pywren   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def delete_cloudobject(co_to_clean, storage_config):
    """
    Deletes cloudobjects from storage
    """
    co_to_delete = []
    for co in co_to_clean:
        co_to_delete.append((co.backend, co.bucket, co.key))

    with tempfile.NamedTemporaryFile(delete=False) as temp:
        pickle.dump(co_to_delete, temp)
        cobjs_path = temp.name

    script = """
    from pywren_ibm_cloud.storage import InternalStorage
    import pickle
    import os

    storage_config = {}
    cobjs_path = '{}'

    with open(cobjs_path, 'rb') as pk:
        co_to_delete = pickle.load(pk)

    internal_storage = InternalStorage(storage_config)

    for backend, bucket, key in co_to_delete:
        if backend == internal_storage.backend:
            internal_storage.storage_handler.delete_object(bucket, key)

    if os.path.exists(cobjs_path):
        os.remove(cobjs_path)
    """.format(storage_config, cobjs_path)

    cmdstr = '{} -c "{}"'.format(sys.executable, textwrap.dedent(script))
    os.popen(cmdstr) 
Example 24
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: take_backup.py    License: MIT License 5 votes vote down vote up
def check_kill_process(pstring):
        # Static method for killing given processes
        for line in os.popen("ps ax | grep " + pstring + " | grep -v grep"):
            fields = line.split()
            pid = fields[0]
            if pid:
                os.kill(int(pid), signal.SIGKILL) 
Example 25
Project: jawfish   Author: war-and-code   File: pydoc.py    License: MIT License 5 votes vote down vote up
def pipepager(text, cmd):
    """Page through text by feeding it to another program."""
    pipe = os.popen(cmd, 'w')
    try:
        pipe.write(text)
        pipe.close()
    except IOError:
        pass # Ignore broken pipes caused by quitting the pager program. 
Example 26
Project: jawfish   Author: war-and-code   File: subprocess.py    License: MIT License 5 votes vote down vote up
def getstatusoutput(cmd):
    """Return (status, output) of executing cmd in a shell.

    Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
    (status, output).  cmd is actually run as '{ cmd ; } 2>&1', so that the
    returned output will contain output or error messages.  A trailing newline
    is stripped from the output.  The exit status for the command can be
    interpreted according to the rules for the C function wait().  Example:

    >>> import subprocess
    >>> subprocess.getstatusoutput('ls /bin/ls')
    (0, '/bin/ls')
    >>> subprocess.getstatusoutput('cat /bin/junk')
    (256, 'cat: /bin/junk: No such file or directory')
    >>> subprocess.getstatusoutput('/bin/junk')
    (256, 'sh: /bin/junk: not found')
    """
    with os.popen('{ ' + cmd + '; } 2>&1', 'r') as pipe:
        try:
            text = pipe.read()
            sts = pipe.close()
        except:
            process = pipe._proc
            process.kill()
            process.wait()
            raise
    if sts is None:
        sts = 0
    if text[-1:] == '\n':
        text = text[:-1]
    return sts, text 
Example 27
Project: jawfish   Author: war-and-code   File: platform.py    License: MIT License 5 votes vote down vote up
def popen(cmd, mode='r', bufsize=-1):

    """ Portable popen() interface.
    """
    import warnings
    warnings.warn('use os.popen instead', DeprecationWarning, stacklevel=2)
    return os.popen(cmd, mode, bufsize) 
Example 28
Project: jawfish   Author: war-and-code   File: __init__.py    License: MIT License 5 votes vote down vote up
def cpu_count():
    '''
    Returns the number of CPUs in the system
    '''
    if sys.platform == 'win32':
        try:
            num = int(os.environ['NUMBER_OF_PROCESSORS'])
        except (ValueError, KeyError):
            num = 0
    elif 'bsd' in sys.platform or sys.platform == 'darwin':
        comm = '/sbin/sysctl -n hw.ncpu'
        if sys.platform == 'darwin':
            comm = '/usr' + comm
        try:
            with os.popen(comm) as p:
                num = int(p.read())
        except ValueError:
            num = 0
    else:
        try:
            num = os.sysconf('SC_NPROCESSORS_ONLN')
        except (ValueError, OSError, AttributeError):
            num = 0

    if num >= 1:
        return num
    else:
        raise NotImplementedError('cannot determine number of cpus') 
Example 29
Project: ansible-logstash-callback   Author: ujenmr   File: logstash.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _init_plugin(self):
        if not self.disabled:
            self.logger = logging.getLogger('python-logstash-logger')
            self.logger.setLevel(logging.DEBUG)

            self.handler = logstash.TCPLogstashHandler(
                self.ls_server,
                self.ls_port,
                version=1,
                message_type=self.ls_type
            )

            self.logger.addHandler(self.handler)
            self.hostname = socket.gethostname()
            self.session = str(uuid.uuid4())
            self.errors = 0

            self.base_data = {
                'session': self.session,
                'host': self.hostname
            }

            if self.ls_pre_command is not None:
                self.base_data['ansible_pre_command_output'] = os.popen(
                    self.ls_pre_command).read()

            if self._options is not None:
                self.base_data['ansible_checkmode'] = self._options.check
                self.base_data['ansible_tags'] = self._options.tags
                self.base_data['ansible_skip_tags'] = self._options.skip_tags
                self.base_data['inventory'] = self._options.inventory 
Example 30
Project: ttbp   Author: modgethanc   File: ttbp.py    License: MIT License 5 votes vote down vote up
def send_feedback(entered, subject="none"):
    '''
    main feedback/bug report handler
    '''

    message = ""

    temp = tempfile.NamedTemporaryFile()
    if entered:
        msgFile = open(temp.name, "a")
        msgFile.write(entered+"\n")
        msgFile.close()
    subprocess.call([SETTINGS["editor"], temp.name])
    message = open(temp.name, 'r').read()

    if message:
        id = "#"+util.genID(3)
        mail = MIMEText(message)
        mail['To'] = config.FEEDBOX
        mail['From'] = config.USER+"@tilde.town"
        mail['Subject'] = " ".join(["[ttbp]", subject, id])
        m = os.popen("/usr/sbin/sendmail -t -oi", 'w')
        m.write(mail.as_string())
        m.close()

        exit = """\
thanks for writing! for your reference, it's been recorded
> as """+ " ".join([subject, id])+""". i'll try to respond to you soon.\
        """
    else:
        exit = """\
i didn't send your blank message. if you made a mistake, please try
running through the feedback option again!\
        """

    return exit