【问题标题】:How do I pass an argument to a php script from python?如何从 python 将参数传递给 php 脚本?
【发布时间】:2021-03-07 16:57:53
【问题描述】:

我有这个 php 脚本:

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

我有这个 python 函数调用它:

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

这是我运行 python 函数时发生的情况:

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:~# 

调用php脚本本身:

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

所以我的论点正在进入 python 函数,但没有被正确传递到 php 脚本中的 $argv[1] 中,但不知道为什么。我从 python 运行 bash 脚本的类似事情中提取了这种语法,并且这种语法可以传递给 bash 脚本的 $1

【问题讨论】:

    标签: python php


    【解决方案1】:

    使用系统 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:])
    

    python3 webAccess.py testing!
    

    返回

    testing! you made it to php
    

    【讨论】:

      【解决方案2】:

      python discord 上的 dzil123 帮助了我,虽然 Monnomcjo 的解决方案可能有效,但走这条路:

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

      正确格式化 subprocess.run() 调用,而不传递我拥有的“脚本”变量,并删除 shell=True

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-23
        • 1970-01-01
        • 2012-08-23
        • 1970-01-01
        • 1970-01-01
        • 2010-10-26
        • 2019-12-20
        相关资源
        最近更新 更多