Oferta Nacional - 234x60

Arquivo

Textos com Etiquetas ‘python’

How to execute python script from php and show output on browser

In this post I will show you how to execute a python script via php, and show the terminal output, in real time, on the browser.

You’ll be able to pass parameters from php to python.

First of all, to show the output on the browser, is realtime, you will need that PHP running in server module mode, not on CGI.

To check it, just run php_info().

We will use basically popen php function (http://br.php.net/manual/pt_BR/function.popen.php) to do it.

The code:


<?php

$param1 = "first";
$param2 = "second";
$param3 = "third";

$command = "python /home/wellington/python_script_example.py";
$command .= " $param1 $param2 $param3 2>&1";

header('Content-Type: text/html; charset=utf-8');
echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
echo "<style type='text/css'>
 body{
 background:#000;
 color: #7FFF00;
 font-family:'Lucida Console',sans-serif !important;
 font-size: 12px;
 }
 </style>";

$pid = popen( $command,"r");

echo "<body><pre>";
while( !feof( $pid ) )
{
 echo fread($pid, 256);
 flush();
 ob_flush();
 echo "<script>window.scrollTo(0,99999);</script>";
 usleep(100000);
}
pclose($pid);

echo "</pre><script>window.scrollTo(0,99999);</script>";
echo "<br /><br />Script finalizado<br /><br />";
?>

And now, the Python script:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Script Python Example
import time
import sys

print "Initializing Python Script"

print "The passed arguments are ", sys.argv

print "Writing lines to a file"

ifile = open( "/tmp/testfile", "w+")
for i in range(0,100):
 ifile.write( "One of the lines of the file\n" )
 print "Printing line ",i," to /tmp/testfile"

ifile.close()

print "Reading and printing lines of /tmp/testfile"
ifile = open( "/tmp/testfile", "r")
for line in ifile:
 print line
ifile.close()
print "End of Python Script"

Posts Relacionados:

Categories: php Tags: , ,

Como ler um arquivo CSV ou TXT usando Python

Continuando o artigo anterior, onde eu tive a necessidade de ler 3 arquivos em formatos de textos mas com padrões diferentes, em que precisei padronizá-los para cadastrar num banco de dados MySQL, vou mostrar como fiz para ler os arquivos CSV e TXT, e depois salvar em arquivos temporários (para manter os originais).



import csv
import re
import os

nome = raw_input("Nome do arquivo: ") # deve ser digitado o caminho do arquivo também

ifile  = open(nome, "r") # arquivo de leitura, original

ofile  = open(nome + ".tmp", "w+") # arquivo temporário, de leitura e gravação

for line in ifile:
linha = line;

#print "Substituindo '\\t\r' por ''"
pattern = re.compile(r'\t\r')
linha = pattern.sub("",linha)

#print "Substituindo ',' por '.'"
pattern = re.compile(r',')
linha = pattern.sub(".",linha)

#print "Substituindo '\t' por ','"
pattern = re.compile('\t')
linha = pattern.sub(",",linha)

#print "Padronizando as datas... \n"
pattern = re.compile(r'([0-9]{2})/([0-9]{2})/([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})')
linha = pattern.sub(r"\3-\2-\1 \4:\5:\6",linha)

print '\n' + line + '\n' + linha + '\n'

ofile.write(linha)

ofile.close()

ifile.close()

Neste ponto, foram feitas algumas substituições utilizando expressões regulares a partir do arquivo original, e salvando num arquivo temporário com a extensão .tmp. Agora vamos abrir o arquivo temporário para leitura. No meu caso, utilizei os dados para cadastrá-los no banco MySQL, mas neste exemplo, apenas vamos imprimir o resultado na tela.



ofile  = open(nome + ".tmp", "rb")
reader = csv.reader(ofile)

rownum = 0
for row in reader:
# Salva o cabeçalho
if rownum == 0:
header = row
else:
colnum = 0
for col in row:


# imprime a linha, com o respectivo nome do campo, salvo do cabeçalho
print '%-8s: %s - %d' % (header[colnum], col, colnum)

colnum += 1

rownum += 1

ofile.close()
os.remove(nome + ".tmp")

 

 

Posts Relacionados:

Como conectar ao MySQL usando Python

Neste post vou mostrar como conectar a uma base de dados MySQL através do Python.

Eu tive essa necessidade quando precisei de converter 3 arquivos de texto diferentes, padronizá-los e cadastrar o resultado no banco de dados, afim de compará-los com outros dados no banco de dados.

Para fazer a conexão ao banco de dados é muito simples:


import MySQLdb

db = MySQLdb.connect('localhost','root','')
cursor = db.cursor()

cursor.execute('INSERT INTO tabela VALUES xxxx')

db.close()

Para consultar e trazer os valores, você pode utilizar assim:


import MySQLdb

db = MySQLdb.connect('localhost','root','')
cursor = db.cursor()

cursor.execute('SELECT * from tabela')

rs = cursor.fetchone() # traz uma linha
rs = cursor.fetchall() # traz todas as linhas
rs = cursor.dictfetchall() # traz todas as linhas e cada coluna com seu respectivo nome
print(rs[0]) # imprime o valor do campo 0 da linha correspondente

db.close()

Se você precisar instalar o módulo MySQL para Python, use

# apt-get install python-mysqldb

Até o próximo!

Related Posts Plugin for WordPress, Blogger...

Posts Relacionados:

SEO Powered by Platinum SEO from Techblissonline