dpafea04148 2015-10-05 22:48
浏览 94

将变量从php传递给python脚本并运行os.system()

I need to set the date and time of my raspberry pi with a php script. After some research I use a php script to call a python script. My datetime.php :

$date = '2015-09-05'; 

$output = shell_exec('/usr/bin/python/home/pi/datalogger/modules/sys/write_date.py ' . $date);

echo $output;

os.system("sudo date -s "+"'"+date_object+"'")

write_date.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from datetime import datetime

def main():
    date=sys.argv[1]
    time='22:04'
    print(date) #for debug

    string_date=date+' '+time+':00'
    date_object2=datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S")
    date_object=date_object2.strftime("%a %b %d %H:%M:%S"+" UTC "+"%Y")
    os.system("sudo date -s "+"'"+date_object+"'")

if __name__ == '__main__':  
    main()

When I refresh my datetime.php I got my date print, so the script works... the problem is that my date is not update. But if I run write_date.py my command line I can update the datetime of raspberry.

  • 写回答

1条回答 默认 最新

  • drnmslpz42661 2015-10-05 23:50
    关注

    An example of setting the date, via PHP, on a Linux based system (E.G. Raspberry Pi):

    <?php
    date_default_timezone_set('UTC');
    $dt = date("D M j G:i:s T Y", strtotime("2015-09-05 22:04"));
    $output = shell_exec('sudo date -s "$dt"');
    ?>
    

    Also strptime() and strftime() exist in PHP:

    http://php.net/manual/en/function.strptime.php

    http://php.net/manual/en/function.strftime.php

    Digging a little deeper, you may need to allow your Web Server to execute /bin/date via an adjustment to /etc/sudoers file. Can add:

    apache <hostname> = (root) NOPASSWD: /bin/date

    Confirm the <hostname> by running cat /etc/hostname. I suspect it is raspberry or raspberrypi. Change it to fit your device.

    To then run, we make one minor change to the script before:

    $output = shell_exec('sudo /bin/date -s "$dt"');

    That should do it. Found this info here: https://unix.stackexchange.com/questions/44865/change-server-date-using-php

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分