PYTHON str_replace en python

Comment faire un equivalent de str_replace() de php en python

La fonction strReplace

1
2
3
4
5
6
7
8
import os
import string
import shutil
 
def strReplace(str, array):
    for search, replace in array:
        str = str.replace(search, replace)
    return str

Utilisation

replace = [(' ', '_'), ('-', '')]
 
for dir in os.listdir('.'):
    newdir = strReplace(dir, replace).capitalize()
    print ("moving: %s > %s"% (dir, newdir))
    os.rename(dir, newdir)

ce qui nous donne dans ce cas précis

moving: Angel of Retribution > Angel_of_retribution
moving: Living After Midnight > Living_after_midnight
moving: British Steel > British_steel
moving: Defenders Of The Faith > Defenders_of_the_faith
moving: Killing Machine > Killing_machine
moving: Ram It Down > Ram_it_down
moving: Hell Bent For Leather > Hell_bent_for_leather
moving: Stained Class > Stained_class
moving: Sin After Sin > Sin_after_sin
moving: Jugulator > Jugulator
moving: Screaming For Vengeance > Screaming_for_vengeance
moving: Turbo > Turbo
moving: Painkiller > Painkiller
moving: Rocka Rolla > Rocka_rolla
moving: Point Of Entry > Point_of_entry
moving: Demolition > Demolition
moving: Priest...Live! > Priest...live!
moving: Sad Wings Of Destiny > Sad_wings_of_destiny

PYTHON Comment faire une requete http

Faire des requetes grace a python et httplib

La class HttpRequest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/python                                                                                        
 
import httplib
import urllib
 
class HttpRequest:
    def __init__(self, proxyhost, proxyport):
        self.proxyhost = proxyhost
        self.proxyport = proxyport
        self.cnx = httplib.HTTPConnection(self.proxyhost, self.proxyport, 20)
 
    def get(self, url):
        self.cnx.request("GET", url)
        response = self.cnx.getresponse()
        print("url: %s, %s %s"%(url, response.status, response.reason))
        self.msg = response.msg
        self.content = response.read()
 
    def post(self, url, params = ''):
        headers = {"Content-type":"application/x-www-form-urlencoded", "Accept":"text/plain"}
        if(len(params) > 0):
            params = urllib.urlencode(params)
        self.cnx.request("POST", url, params, headers)
        response = self.cnx.getresponse()
        print("url: %s, %s %s"%(url, response.status, response.reason))
        self.msg = response.msg
        self.content = response.read()
 
    def getresponse(self):
        print(self.msg)
 
    def getcontent(self):
        print(self.content)
 
    def __del__(self):
        self.cnx.close()
httprequest = HttpRequest("127.0.0.1", "3777")

En GET

httprequest.get('http://www.google.fr')
httprequest.get('http://blog.hio.fr')
httprequest.get('http://blog.hio.fr/blu.html')
httprequest.get('http://blog.if-else.fr')

Renvoi

url: http://www.google.fr, 200 OK
url: http://blog.hio.fr, 200 OK
url: http://blog.hio.fr/blu.html, 404 Not Found
url: http://blog.if-else.fr, 200 OK

En POST

params = {"login":"login",
          "password":"password"}
httprequest.post('http://www.url-bidon.fr/login/connexion', params)

Renvoi par exemple

url: http://www.url-bidon.fr/login/connexion, 302 Moved Temporarily

Et si on veut en savoir plus on a les fonctions getresponse() et getcontent()

httprequest.getresponse()

Renvoi

Date: Sun, 15 Nov 2009 11:04:55 GMT
Server: Apache
X-Powered-By: PHP/5.2.6-1+lenny3
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: PHPSESSID=d1d0958e52fb25b874a573bd1c261b1a; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Location: /login/failed
Vary: Accept-Encoding
Content-Length: 0
Content-Type: text/html; charset=utf-8
X-Cache: MISS from proxy.hio.fr
X-Cache-Lookup: MISS from proxy.hio.fr:3777
Via: 1.0 proxy.hio.fr (squid/3.0.STABLE8)
Proxy-Connection: close
httprequest.getcontent()

Renvoi le contenu de la page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
 
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 
etc...

PHP Fork it

1
2
3
4
5
6
7
<?php
function test($max) {
  for($i = 0; $i < $max; $i++) {
 
  }
  }
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
class fork {
  private $children = array();
 
  public function __construct($threads) {
    $this->timestart = microtime(true);
    $this->threads = $threads;
  }
 
  public function forker($worker, $data) {
    foreach($data as $row) {
      $pid = pcntl_fork();
      if($pid == -1 ) {
        exit(1);
      } elseif($pid) {
        echo ' PARENT | launching thread (pid: '.$pid.')'."\n";
        $this->children[] = $pid;
        if(count($this->children) >= $this->threads) {
          $pid = array_shift($this->children);
          pcntl_waitpid($pid, $status);
        }
      } else {
        echo ' CHILD  | working on '.$worker.'('.$row.')'."\n";
        $worker($row);
        echo ' CHILD  | finish '.$worker.'('.$row.')'."\n";
        exit(0);
      }
    }
  }
 
  public function waitchildrens() {
    foreach($this->children as $child) {
      pcntl_waitpid($child, $status);
    }
  }
 
  public function time() {
    $timeend = microtime(true);
    $time = $timeend - $this->timestart;
    echo ' TIME   | '.$time.' seconde(s)'."\n";
  }
}
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
$fork = new fork(4);
$fork->forker('test', array('11111111',
                            '22222222',
                            '33333333',
                            '44444444',
                            '55555555',
                            '66666666',
                            '77777777',
                            '88888888'));
$fork->waitchildrens();
$fork->time();
?>