0

I got a python script in crontab writing in a file 24/7 because is always getting information and writing on file FILE.txt.

I run another script on crontab to get that content and send to a database (just what I want) and then truncate file.

But what happen? Lets suppose the file have 1000 bytes and I clear with that second script, the file after writing on it will have 1000 bytes + new bytes.

That 1000 bytes are strange symbols on file something like (?)(?)(?)(?)(?)

I tried the following:

file.seek(0)
file.truncate(0)

But without success.

Henrique Mota
  • 134
  • 1
  • 11
  • Are you truncating file which is still open in another process? – Alex Sveshnikov Mar 06 '20 at 09:47
  • You really shouldn't edit file concurrently that will always cause problems. – miszcz2137 Mar 06 '20 at 09:51
  • @Alex yes, its opened in another screen. – Henrique Mota Mar 06 '20 at 09:53
  • @miszcz2137 how should I do this then? :/ – Henrique Mota Mar 06 '20 at 09:53
  • 1
    Your "24/7" script should coordinate with your "log-rotation" script. – Alex Sveshnikov Mar 06 '20 at 09:56
  • 2
    see this https://stackoverflow.com/questions/489861/locking-a-file-in-python – miszcz2137 Mar 06 '20 at 09:57
  • 1
    Also not even if you fix this more efficient would be if both task aren't scheduled at the same time (for example do one at full hour, other five past full hour) – miszcz2137 Mar 06 '20 at 10:02
  • I think this question needs some clarification. A cron script is run periodically. IMO it cannot be "always writing". – VPfB Mar 06 '20 at 10:38
  • Crontab *@reboot screen -dmS bTCP; sleep 5; screen -S bTCP -X stuff '/usr/sbin/tcpdump -i any port 3306 -s 65535 -x -nn -q -tttt> /path/to/tcpdump_3306.out\n'* @VPfB – Henrique Mota Mar 06 '20 at 11:04
  • That will run a new screen with that, always writing. Then I use **0 12 * * * /usr/bin/python /path/to/scripts/test.py** – Henrique Mota Mar 06 '20 at 11:04
  • 1
    @HenriqueMota Thank you for adding the information about ``@reboot`` cron extension. I think the design with one ever increasing file is very disadvantageous. I don't know an answer for the general case as in the question title (how to clear a file ...), but I think, there is a solution. The ``tcpdump`` can do some *raw* data file rotation. See the man page, options ``-w raw-data-file`` , ``-G rorate-seconds``, and ``-z postrotate-command ``. Also ``-r`` for reading the saved file in the postrotate-command. Hope this helps. – VPfB Mar 06 '20 at 14:07

0 Answers0