yusuf yusuf - 4 years ago 97
Python Question

Changing the value in a file dynamically from python

I have a php file. And in the php file, I have such a statement:

"$limit_value = ..."

I want to change this limit value dynamically by using python. It means, there is no any default limit value. It is going to change whenever I run the python statement. And the .php file will be modified.

For instance,

"$limit_value = 5"
"$limit_value = 500"
"$limit_value = 34"

I have found similar solutions on stackoverflow, but none of them references to the exact issue of mine.

Could you give me a simple example to solve my issue?


Answer Source

Assuming you have a index.php and it looks something like this:

    $limit_value = 0;
    echo $limit_value;

You could in python do:

import re
rep = re.compile('\$limit_value =.*;')

with open('/path/to/file/index.php', 'r+') as php:
    data = rep.sub('$limit_value = 5', php.read())
    php.seek(0) # Places the text "Input" in the file at the beginning of the file
    php.truncate() # This will cause all trailing data to be flushed.
                            # reason for doing this is because your default value of `$limit_value` might
                            # make your total content written back to the file shorter of that was writter before.
                            # there for there might be trailing data we need to truncate away.

This will create a regexp object that will find anything named $limit_value =<anything>; and replace it with $limit_value = 5; assuming 5 is the default value you want to use.

Verified: http://i.imgur.com/FNvRmHy.png

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download