I am creating a file and then doing diff on it.
I want to do diff on the file which iscreated in previous step but i get the error that file dont exist .
This is my code
os.popen("mysqldump --login-path=server1_mysql -e --opt --skip-lock-tables --skip-extended-insert -c %s > %s.sql" % (database, filename))
os.popen("diff %s %s > %s" % (weekly, filename, filename+".PATCH"))
os.popen()
has been deprecated since version 2.6. However, to get your code working, you should wait for the first process to finish (and the output file to be created) before starting the second.
The exit status of the first command is available as the return value of the close()
method of the file object returned, so you can check that before continuing, i.e.:
pipe = os.popen("mysqldump --login-path=server1_mysql -e --opt "
"--skip-lock-tables --skip-extended-insert -c %s > %s.sql" %
(database, filename))
if pipe.close() is None: # no errors?
os.popen("diff %s %s > %s" % (weekly, filename, filename+".PATCH"))
os.popen
is deprecated. Use the subprocess module. subprocess.call
will block the main process until the command is finished. You should inspect the returncode, retval
, in case there was an error while executing the mysqldump
command. In that case, you can not continue with the diff
:
import subprocess
import shlex
with open("{f}.sql".format(f=filename), 'w') as fout:
retval = subprocess.call(
shlex.split(
"""mysqldump --login-path=server1_mysql -e --opt --skip-lock-tables
--skip-extended-insert -c %s""" % (database, )),
stdout=fout)
if not retval == 0:
raise Exception('Error executing command: {r}'.format(r=retval))
else:
with open("{f}.PATCH".format(f=filename), 'w') as fout:
retval = subprocess.call(
shlex.split("diff {w} {f}".format(w=weekly, f=filename)),
stdout=fout)
A super simple way is to use busy waiting:
os.popen("mysqldump --login-path=server1_mysql -e --opt --skip-lock-tables --skip-extended-insert -c %s > %s.sql" % (database, filename))
while not os.path.isfile(filename):
sleep(0.05) # or some other interval
os.popen("diff %s %s > %s" % (weekly, filename, filename+".PATCH"))
EDIT:
Use with care, leaves a race condition because the condition that is being checked is only that the file exists, not the the previous process is finished writing.