【问题标题】:PHP/Python bizarre behaviorPHP/Python 奇怪的行为
【发布时间】:2017-09-28 00:47:30
【问题描述】:

我不明白为什么它适用于不同的文件而不适用于共享文件。任何能解开这个谜团的英雄都是我的冠军。

所以这就是我想要做的,PHP 脚本将数据写入文件。 0,1 或 -1。从 python 脚本中读取相同的文本文件,并使伺服电机根据 -1 或 1 和 0 向左或向右移动。如果我自己创建一个虚拟文本文件并让 python 读取它,它就像一个魅力,但是当我让 python 脚本读取 PHP 修改的文本文件时,它会在控制台中打印值但伺服器不会移动!!!我不知道是否存在读/写混乱或 0 和 1 的写入方式。这是代码。

PHP 脚本:

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");

if ($_POST['leftb'])           
{ echo "Left is pressed";      // If Left button is pressed
    $txt = -1;}                // Set txt to -1


else if ($_POST['rightb'])
{ echo "Right is pressed";     // If Right button is pressed
    $txt = 1;}                 // Set txt to 1


fwrite($myfile, $txt);        // Write the value to file
fclose($myfile);              // Close file



sleep(1);                     // Wait 1 second

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = 0;                     // Reset previous value to 0
fwrite($myfile, $txt);        // Write to the same file
fclose($myfile);              // Close the file

?>

Python 脚本:

# System initialization on Raspberry Pi 3
import time
import RPi.GPIO as GPIO
initial = 5
GPIO.setmode(GPIO.BOARD)
GPIO.setup(38,GPIO.OUT)
pwm=GPIO.PWM(38,50)

# Set the servo position in the middle (5)
pwm.start(5)
position = initial

while True:

    f = open("newfile.txt","r")    # Read file written by PHP for value
    x = f.read();
    x = int(x)                     # Make sure its an integer value

    position = position + x        # Increment or decrement initial position 


    if position != initial:        # If position is different from initial position, update the servo position
        pwm.ChangeDutyCycle(position)
        print position         # Print to screen the current servo position

    else: 
        pwm.stop()             # If no new position detected, stop the servo


        f.close()              # Close the text file 
    time.sleep(0.8)

如您所见,两个程序之间共享一个通用文本文件。该文件的名称是“newfile.txt”。当我打开它时,我可以手动查看由 php 脚本写入的数据,或者只是在终端上查看 python 的输出,只是它实际上并没有旋转伺服。如果我创建一个新的文本文件并手动写入 -1 或 1 或 0 并且伺服将完美地移动,同样的事情会起作用。

我不明白为什么两个文本文件中的相同 -1 或 1 彼此不同?一个字符和另一个整数?我真的可以求助!

【问题讨论】:

  • 我责怪换行符。发帖cat -vet newfile.txt
  • 不知道您的意思是什么,请您详细说明您的意思吗?谢谢@bishop
  • 我的猜测是,文件在编辑时与由 PHP 创建时的行尾不一致,您的程序无法处理。 cat 是 UNIX 机器上的命令。 -vet 参数适用于 GNU/Linux 机器以在文件中显示不可打印的字符。如果你没有,那么我建议使用一个程序,它可以显示文件中的实际字节并仔细检查行尾(并且你没有杂散的非打印字符)。
  • 哦,我现在明白你的意思了,这两个程序都在树莓派上运行。所以你建议我在 newfile.txt 之前添加 -vet 命令?就像写或打开或关闭时一样?
  • 但问题仍然存在,python如何能够在终端中完美地打印出这些值?它甚至添加和减去它们!如果出现问题,他们就不会出现。

标签: php python html raspberry-pi


【解决方案1】:

您是否检查过这两个文件是否具有相同的编码,例如(ASCII 与 Unicode)?

【讨论】:

    猜你喜欢
    • 2014-07-08
    • 2013-08-09
    • 2021-11-21
    • 2018-05-20
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多