简体   繁体   English

如何将参数从 python 传递给 php 脚本?

[英]How do I pass an argument to a php script from python?

I have this php script:我有这个 php 脚本:

<?php
$argOne = $argv[1];
print "$argOne";
print "you made it to php";

And I have this python function calling it:我有这个 python function 调用它:

def phpCall(argOne):
    script = 'php ./phpScript'
    proc = subprocess.run([script, argOne], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    print(proc)
    script_response = str(proc.stdout,'utf-8')
    return script_response

this is what happens when I run the python function:这就是我运行 python function 时发生的情况:

root@testSrv:~# python3 webAccess.py 
CompletedProcess(args=['php ./phpScript', 'testArgument'], returncode=0, stdout=b'you made it to php', stderr=b'')
you made it to php
root@testSrv:~# 

Calling the php script itself:调用 php 脚本本身:

root@testSrv:~# php phpScript argumentOne
argumentOneyou made it to phproot@testSrv~# 

So my argument is making its way into the python function, but is not being passed correctly to be assinged to $argv[1] in the php script but not sure why.所以我的论点正在进入 python function,但没有被正确传递给 php 脚本中的 $argv[1],但不确定为什么。 I yanked this syntax out of a similar thing I was doing running a bash script from python, and this syntax worked to pass to the bash script's $1我从类似的事情中抽出了这个语法,我正在从 python 运行 bash 脚本,并且这个语法可以传递给 bash 脚本的 $1

use sys argv:使用系统 argv:

import subprocess
from sys import argv

def phpCall(argOne):
    proc = subprocess.Popen("php phpScript.php "+argOne, shell=True, stdout=subprocess.PIPE)
    script_response = proc.stdout.read()
    print(script_response)
    return script_response

phpCall(*argv[1:])

And

python3 webAccess.py testing!

Returns退货

testing! you made it to php

dzil123 on the python discord helped me out, and while Monnomcjo's solution may work went this route: python discord 上的 dzil123 帮助了我,虽然 Monnomcjo 的解决方案可能有效,但走这条路:

proc = subprocess.run(['php', '-f', './phpScript', argOne], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

to format the subprocess.run() call correctly, without passing in the 'script' variable I had, and removing shell=True正确格式化 subprocess.run() 调用,而不传递我拥有的“脚本”变量,并删除 shell=True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM