简体   繁体   中英

Python os.system: Order of commands

Why does calling the file a.py with content

import os
print('Hi')
os.system('cat a.py')

yield the following output and how can I get them to print in the correct order?

$ python a.py
import os
print('Hi')
os.system('cat a.py')
Hi

You see that the cat command prints to stdout before print does. Happens when running Python 3.6 in GitBash on Windows 10. Does not happen with Python 3.6 on Ubuntu 17.10.


Note: I'm aware that I can get around printing the content of a file with something like file.readlines() easily. This is just a simple example. However, when running something more complex, it can become important to understand why this happens and how to get around it

Output is buffered. You have to flush this buffer:

import os
import sys
print('Hi')
sys.stdout.flush()
os.system('cat a.py')

That is a cleaner way of doing it.

from subprocess import check_output  
print check_output(['cat', 'a.py'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM