简体   繁体   English

PHP无法执行创建的命令,但是exec()和system()正常工作

[英]PHP Unable to execute created command, but exec() and system() work properly

I'm facing a problem where PHP is able to execute CMD commands on Windows properly, but when I create a custom command to run, nothing works. 我遇到的问题是PHP能够在Windows上正确执行CMD命令,但是当我创建要运行的自定义命令时,没有任何效果。

Logic: I want to "cd" into a directory and then run python script that will scrape data from the web and save it in csv. 逻辑:我想“进入”目录,然后运行python脚本,该脚本将从Web上抓取数据并将其保存在csv中。 Python script works fine. Python脚本工作正常。

PHP Code: PHP代码:

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    $keyword = $_POST['singleSearchTerm'];
    $filename = $_POST['singleFilename'];
    $settings = file('settings.txt', FILE_SKIP_EMPTY_LINES);
    $conda_path = $settings[0];
    $working_env = $settings[1];
    $script = "scrape.py";
    $url = "https://www.pinterest.com/search/pins/?q=";
    $current_dir = getcwd();

    // cd into path
    $cd_path = "cd " . $conda_path . "&& ";

    // activate env
    $activate_env = "activate " . $working_env . " && cd ";

    // run python script
    $pyCommand = $current_dir . "\\ps\\ " . " && python -W ignore ". $script . " --url " . $url . $keyword . " --fname " . $filename;

    // full command
    $full_command = $cd_path . $activate_env . $pyCommand;

    echo $full_command;

    // test - works fine
    exec("start notepad.exe");

    // doesn't do anything
    exec($full_command);

    // doesnt do anything
    system($full_command)
}

Generated Command: After the above PHP is loaded, the following command is generated: 生成的命令:加载上述PHP之后,将生成以下命令:

cd C:\Users\da74\Anaconda3\Scripts && activate scrape && cd C:\MAMP\htdocs\pinscraper\ps\ && python -W ignore scrape.py --url https://www.pinterest.com/search/pins/?q=old --fname dat.csv

Issue: When the above command is pasted in CMD, it runs. 问题:将以上命令粘贴到CMD中后,它就会运行。 But when it's passed using exec() or system() in PHP, it doesn't run. 但是,当它在PHP中使用exec()或system()传递时,它不会运行。

Tested: Have tested: 已测试:已测试:

exec("start notepad.exe");

and it opens a notepad window. 它会打开一个记事本窗口。 I don't know what's the problem. 我不知道出什么问题了。 Is it hidden spaces? 是隐藏空间吗? or something else? 或者是其他东西?

Any help is appreciated. 任何帮助表示赞赏。 Thankyou 谢谢

I got alternative method to run it using NodeJS. 我有使用NodeJS运行它的替代方法。

It anyone looking for the same problem, found out that PHP leaves unusual spaces after and before '&&' and sometimes a line break for no reason. 有人在寻找相同的问题时,发现PHP在'&&'前后都留有不寻常的空格,有时会无故断行。

For this, I installed nodejs. 为此,我安装了nodejs。 Then made the PHP to save each var in a settings file line by line and let nodejs form a command to run using 'process' and exec. 然后使PHP逐行将每个var保存在设置文件中,并让nodejs形成一个使用'process'和exec运行的命令。 It works perfectly and only needs few lines of code. 它运行完美,只需要几行代码。

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

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