【问题标题】:Python doesn't restart the linux process properlyPython 没有正确重启 linux 进程
【发布时间】:2012-12-31 08:36:17
【问题描述】:

我有一个 PHP 项目,我使用 Python 将它部署在生产服务器上。

这是部署计划:

  1. 找到新的php.ini文件(路径已定义)

  2. 用这个文件替换当前文件

  3. 通过os.system('service php-fastcgi restart')重启PHP-FPM进程,其中php-fastcgi是进程的真实名称。

Python 在执行脚本期间没有显示任何错误,但 PHP 会以默认配置重新启动。当我尝试手动重新启动它时(在 Linux 终端中),它运行良好,并且新的 php.ini 配置成功加载。你能解释一下我的 Python 脚本的这种奇怪行为吗?

更新

这是 Python 脚本的一部分。

    php_ini_path_replace = '/etc/php5/cgi/php.ini'
    php_ini_path_source = os.path.join(destination, 'production', 'config', 'main-php.ini')

    try:        # Read source file
        source_conf_file = open(php_ini_path_source, 'r')
        php_ini_lines = source_conf_file.readlines()
    except IOError:
        print('Something is wrong with source file')

    try:
        actual_conf_file = open(php_ini_path_replace, 'w')
        actual_conf_file.writelines( php_ini_lines )
        print('PHP CGI configuration was succesfully changed.\nDon\'t forget to restart the PHP')
    except IOError:
        print('Something is wrong with actual file. May be it\'s in use')

os.system('service php-fastcgi restart')

【问题讨论】:

  • 发布你正在谈论的实际脚本怎么样?
  • 谢谢! Python 不是我的菜。重写文件之前不需要清理文件句柄吗?也许尝试获得独占文件锁?至少这些是我在其他语言中会担心的事情。

标签: php python linux process


【解决方案1】:

使用copyfile 而不是手动打开和关闭文件。

import shutil

php_ini_path_replace = '/etc/php5/cgi/php.ini'
php_ini_path_source = os.path.join(destination, 'production', 'config', 'main-php.ini')

try:
    shutil.copyfile(php_ini_path_source, php_ini_path_replace)
except (Error,IOError):
    print('Error copying the file')

os.system('service php-fastcgi restart')

【讨论】:

    【解决方案2】:

    writelines() 写入的数据可能会保留在进程内缓存中,直到文件被刷新(如在 C 中)。之后启动的其他进程可能会看到一个空文件或部分文件。写完后需要添加的是source_conf_file.close()。 (这是一个烦人的问题,因为当 Python 进程完成时,然后文件会被刷新,如果您之后尝试查看它,它会显示正确。)

    【讨论】:

    • 谢谢!一会试试看
    【解决方案3】:

    我觉得你最好把shell cmd的返回码或者字符串粘贴一下,这样可以帮助我们找到根本原因。

    一些建议:

    记得关闭文件处理程序。您可以使用with。喜欢:

    try:
        with open(php_ini_path_source, 'r') as source_conf_file:
            php_ini_lines = source_conf_file.readlines()
    except IOError:
        print('Something is wrong with source file')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      • 2010-09-14
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      相关资源
      最近更新 更多