欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python如何調用php文件中的函數(shù)詳解

 更新時間:2020年12月29日 10:46:57   作者:xiaofeiyuan  
這篇文章主要給大家介紹了關于python如何調用php文件中函數(shù)的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

前言

python調用php代碼實現(xiàn)思路:php文件可通過在terminal中使用php命令行進行調用,因此可使用python開啟子進程執(zhí)行命令行代碼。函數(shù)所需的參數(shù)可通過命令行傳遞。

測試環(huán)境

1、操作系統(tǒng):macos10.13.2

2、php版本:PHP 7.1.7(mac自帶)

3、python版本:python3.6.0

4、python庫:subprocess

調用php函數(shù)

php命令行調用php文件中的函數(shù)

php文件:test_hello.php

<?php


function hello_world($s1)
{
	$str1 = $s1;
	echo $str1;
	echo "\n";
}

function hello_world2($s1, $s2)
{
	$str1 = $s1;
	$str2 = $s2;
	echo $s1;
	echo "**********";
	echo $s2;
	echo "\n";
}

// 獲取參數(shù),索引為0為調用的文件路徑,索引為1為調用的函數(shù),索引為2為函數(shù)傳入?yún)?shù)$s1,索引為3為函數(shù)參數(shù)$s2

var_dump($argv);
// exit;

// 調用函數(shù)
$func_name = $argv[1];


if ($func_name == "hello_world")
{
	// 參數(shù)1
	$param1 = $argv[2];
	hello_world($param1);
}
elseif ($func_name == "hello_world2")
{
	// 參數(shù)1
	$param1 = $argv[2];
	// 參數(shù)2
	$param2 = $argv[3];
 hello_world2($param1, $param2);
}
else
{
 echo "the function $func_name is not exist !";
}

?>

terminal執(zhí)行php命令

# 字符串中包含空格、逗號、反斜杠,需要使用""來確定為1個參數(shù)
php -f test_hello.php hello_world "My name is John\\, age is 20."
php -f test_hello.php hello_world2 "My name is John\\, age is 20." "My hometown is BaoDing."
php -f test_hello.php hello_world3 "My name is John\\, age is 20."

執(zhí)行結果

python子進程執(zhí)行php命令行

python文件:test.py,將test_hello.php與test.py放在同目錄下運行

import subprocess


class Test(object):
 def run(self, cmd):
 proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) # 開啟子進程
 res = proc.stdout.read()
 if res:
  res = res.decode()
 return res


cmd1 = 'php -f test_hello.php hello_world "My name is John\\, age is 20."'
cmd2 = 'php -f test_hello.php hello_world2 "My name is John\\, age is 20." "My hometown is BaoDing."'
cmd3 = 'php -f test_hello.php hello_world3 "My name is John\\, age is 20."'
obj = Test()
for i in [cmd1, cmd2, cmd3]:
 res = obj.run(cmd1)
 print(res)
 print("*" * 10)

到此這篇關于python如何調用php文件中函數(shù)的文章就介紹到這了,更多相關python調用php函數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論