Does the python code executes in order

两盒软妹~` 提交于 2019-12-12 04:56:00

问题


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"))

回答1:


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"))



回答2:


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)



回答3:


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.



来源:https://stackoverflow.com/questions/17651300/does-the-python-code-executes-in-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!