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: _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 #3
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 #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: 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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #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: 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 #14
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 #15
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 #16
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 #17
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 #18
Source File: _cpmodpy.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def popen(fullcmd):
        pipein, pipeout = os.popen4(fullcmd)
        return pipeout 
Example #19
Source File: _cpmodpy.py    From cherrypy with 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 #20
Source File: gen.py    From multibootusb with 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 #21
Source File: Server.py    From EvilOSX with 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 #22
Source File: utils.py    From pywren-ibm-cloud with 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 #23
Source File: take_backup.py    From MySQL-AutoXtraBackup with 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 #24
Source File: pydoc.py    From jawfish with 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 #25
Source File: platform.py    From jawfish with 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 #26
Source File: __init__.py    From jawfish with 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 #27
Source File: logstash.py    From ansible-logstash-callback with 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 #28
Source File: ttbp.py    From ttbp with 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 
Example #29
Source File: augt.py    From pydiogment with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def eliminate_silence(infile):
    """
    Eliminate silence from voice file using ffmpeg library.

    Args:
        - infile  (str) : Path to get the original voice file from.

    Returns:
        list including True for successful authentication, False otherwise and
        a percentage value representing the certainty of the decision.
    """
    # define output name if none specified
    output_path = infile.split(".wav")[0] + "_augmented_without_silence.wav"

    # filter silence in wav
    remove_silence_command = ["ffmpeg", "-i", infile,
                              "-af",
                              "silenceremove=stop_periods=-1:stop_duration=0.25:stop_threshold=-36dB",
                              "-acodec", "pcm_s16le",
                              "-ac", "1", output_path]
    out = subprocess.Popen(remove_silence_command,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
    out.wait()

    with_silence_duration = os.popen(
        "ffprobe -i '" + infile +
        "' -show_format -v quiet | sed -n 's/duration=//p'").read()
    no_silence_duration = os.popen(
        "ffprobe -i '" + output_path +
        "' -show_format -v quiet | sed -n 's/duration=//p'").read()
    return with_silence_duration, no_silence_duration 
Example #30
Source File: kaldi_io.py    From Attentive-Filtering-Network with MIT License 5 votes vote down vote up
def open_or_fd(file, mode='rb'):
  """ fd = open_or_fd(file)
   Open file, gzipped file, pipe, or forward the file-descriptor.
   Eventually seeks in the 'file' argument contains ':offset' suffix.
  """
  offset = None
  try:
    # strip 'ark:' prefix from r{x,w}filename (optional),
    if re.search('^(ark|scp)(,scp|,b|,t|,n?f|,n?p|,b?o|,n?s|,n?cs)*:', file):
      (prefix,file) = file.split(':',1)
    # separate offset from filename (optional),
    if re.search(':[0-9]+$', file):
      (file,offset) = file.rsplit(':',1)
    # input pipe?
    if file[-1] == '|':
      fd = popen(file[:-1], 'rb') # custom,
    # output pipe?
    elif file[0] == '|':
      fd = popen(file[1:], 'wb') # custom,
    # is it gzipped?
    elif file.split('.')[-1] == 'gz':
      fd = gzip.open(file, mode)
    # a normal file...
    else:
      fd = open(file, mode)
  except TypeError:
    # 'file' is opened file descriptor,
    fd = file
  # Eventually seek to offset,
  if offset != None: fd.seek(int(offset))
  return fd

# based on '/usr/local/lib/python3.4/os.py'