Search code examples
pythonshellcachingpsqltimescaledb

Clear memory cache from python


I am using python because i try to run some queries from psql in cold state in a for loop.So before the execution of every query my cache must be clear! I imported os and then i did this:

if state=="cold":
         os.system('sudo sh -c "sync; echo 3 > /proc/sys/vm/drop_caches"')

I am getting this output:

sh: 1: cannot create /proc/sys/vm/drop_caches: Permission denied

sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper

I dont know how to fix this.


Solution

  • acorrding to this stack question:

    how to pass sudo password from python script

    you can try this:

    password = 'my sudo password'
    command = 'sh -c "sync; echo 3 > /proc/sys/vm/drop_caches"'
    
    # formatting the sudo password and the command
    shell_script = f"echo {password} | sudo -S {command}"
    
    # running the script
    os.system(shell_script)