0
我一直在嘗試在php中使用popen命令執行多處理的python程序。使用popen執行多處理腳本時出現亂碼
問題是,輸出順序不符合預期。 PHP代碼是
if (($fp = popen("python multi-processed.py 2>&1", "r")))
{
while(!feof($fp))
{
print fread($fp, 1024);
ob_flush();
flush();
}
fclose($fp);
}
else
print "can't execute command";
但是當我運行殼這個命令,我得到輸出預計爲了
python multi-processed.py 2>&1
然後我想到管道緩衝,並用C
下面的代碼寫FILE *fp = popen("python multi-processed.py -u", "r");
if(fp != NULL)
{
setvbuf(fp, 0, _IONBF, 0);
while (!feof(fp))
{
fgets(buffer, 1024, fp);
puts(buffer);
fflush(fp);
}
fclose(fp);
}
在這裏,我通過調用setvbuf(fp, 0, _IONBF, 0);
來關閉管道緩衝,但輸出順序不符合預期。
編輯:新增Python文件:multi-processed.py
def foo():
print 'in foo'
sleep(2)
print 'in foo after sleep'
def fun():
print 'in fun'
sleep(2)
print 'in fun after sleep'
if __name__ == '__main__':
p1 = Process(target=foo, args=())
p2 = Process(target=fun, args=())
p1.start()
p2.start()
p1.join()
p2.join()
預期輸出:
in foo
in fun
in foo after sleep
in fun after sleep
實際輸出:
in foo
in foo after sleep
in fun
in fun after sleep
能否請你幫我在這?
PS:我使用的是Windows機器,不能運行像unbuffer
「多處理」 程序?還是多線程? – deviantfan
多處理程序@deviantfan – Akshay