drk7700
2018-07-16 11:57
浏览 192
已采纳

使用shell_exec写入Python中的文本文件

So first off, sorry if this question has already been answered elsewhere, but I couldn't find the answer myself.

I've got a LAMP server running in Ubuntu 16.04 and I'm trying to use Python 2.7.12 to write to a text file from PHP.

I've got the following two files (note, these two files are in the same directory):

index.php

<?php
    $command = escapeshellcmd('python test.py a b c');
    $output = shell_exec($command);
    echo $output;
?>

test.py

import sys

print "argv1: ", sys.argv[1]
print "argv2: ", sys.argv[2]
print "argv3: ", sys.argv[3]

f = open("test-" + sys.argv[1] + ".txt","w+")
f.write("test")
f.close()

print "Text added."

When I navigate to the index.php file in my browser, I get the following output:

argv1: a argv2: b argv3: c

However, when I execute this code in the terminal the file test-a.txt is created and I get the following output:

layer8@alpha:/var/www/html/$ python test.py a b c
argv1:  a
argv2:  b
argv3:  c
Text added.

I can't seem to understand and work out why the Python file isn't executing any code past the third print argv3 statement?

I've done a lot of research into this and I've been unable to find a solution. If you need any further information from me, please do not hesitate to ask; any responses are appreciated.

Thanks.

图片转代码服务由CSDN问答提供 功能建议

首先,对不起,如果这个问题已在其他地方得到解答,但我自己找不到答案。

我在 Ubuntu 16.04 中运行了一个LAMP服务器,我正在尝试使用 Python 2.7.12 来写入 来自PHP的文本文件。

我有以下两个文件(注意,这两个文件 在同一目录中): \ n

index.php

 &lt;?php 
 $ command = escapeshellcmd('python test.py ab c')  ; 
 $ output = shell_exec($ command); 
 echo $ output; 
?&gt; 
   
 
 

test.py

  import sys 
 
print“argv1:”,sys.argv [1] 
print“argv2:”,sys.argv [2] 
print“argv3:”  ,sys.argv [3] 
 
f = open(“test-”+ sys.argv [1] +“。txt”,“w +”)
f.write(“test”)
f.close()  
 
print“已添加文字。”
   
 
 

当我在浏览器中导航到index.php文件时,我得到以下输出: \ ñ

<代码> argv1 :a argv2:b argv3:c

但是,当我在终端中执行此代码时,会创建文件 test-a.txt , 我得到以下输出:

  layer8 @ alpha:/ var / www / html / $ python test.py abc 
argv1:a 
argv2:b 
argv3:c \  nText添加。
   
 
 

我似乎无法理解并弄清楚为什么Python文件没有执行超过第三个print argv3语句的任何代码?

我已经对此进行了大量研究,但我一直无法找到解决方案。 如果您需要我的任何进一步信息,请不要犹豫; 任何回复都表示赞赏。

谢谢。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新