Here's the deal:
#!/usr/bin/env python3
import subprocess
from subprocess import Popen, PIPE
var = '* * * * * mkdir /etc/STATISTICS\n'
try:
with open('./.file_temp', 'w') as f:
f.write(var)
p1 = Popen(['crontab', '-e'], stdout=PIPE, stdin=open('./.file_temp', 'r'), shell=True)
print ('The first one got executed.')
except FileNotFoundError:
subprocess.run(['touch', './.file_temp'])
f.write(var)
p1 = Popen(['crontab', '-e'], stdout=PIPE, stdin=open('./.file_temp', 'r'), shell=True)
print ('The second got executed.')
delete = Popen(['rm', '-f', './.file_temp'])
print ('The temp file has been deleted.')
Firstly, the code that you are looking at is a dummy code I made just so you can see what's bugging me - the real one is somewhat nicer.
So, I wanted to use Popen to start crontab -e
and append whatever is found in the variable called var
. I tried
stdin=var
but that gives me AttributeError: 'str' object has no attribute 'fileno'
, which led me to make a file that will store my variable. Now, that file serves as an input parameter for crontab -e
, which is initiated by the Popen itself.
When I run it, it works like a charm. In the crontab, I see my variable that is indeed executed. Awesome!
Buuut, here's the catch: whenever I start this small program of mine, it would delete everything that was in the crontab file prior to the program execution and write the content of the .file_temp
to the crontab file. I don't want that. I want to append to the crontab file, instead of deleting everything and inputting only what's in that temporary file.
That .file_temp
is no longer a temp file since it has to exists on the system with all commands (exclusively given by my program), otherwise, it will get rid of everything...which is not the desired effect.
Imagine someone manually writes something to the crontab file and then after some time decides to use my program. Well in that case, if my program gets initiated, it will load only things defined within itself (referring to the .file_temp), and nicely run over manually given commands.
For short, how to append something to a program run by Popen?
NOTE: This is done in Linux (Ubuntu). I am kind of a beginner, so yeah, I might have missed something obvious. I've checked everything before coming here but I haven't found any concrete answers.
It is possible that I have messed something up with stdout
and stdin
since I am not 100% clear on those concepts.