3

Consider the following sample script:

import os
import sys

print(1)
os.execl(sys.executable, sys.executable, '-c', 'print(2)')
print(3)

The result is

1

I was expecting

1
2

I think it is because the replacing process is not using the same stdin/stdout/stderr?

How can I achieve what I was expecting for while using execl?

I'm using Python 3.6 on Windows.

AXO
  • 8,198
  • 6
  • 62
  • 63
  • 2
    Cannot reproduce with Python 3.6.2 on windows 10. Simply the `2` comes after the cmd prompt. – Serge Ballesta Dec 19 '17 at 08:26
  • @SergeBallesta, Thanks! I was running the script in PyCharm and, for some reason, it does not print the `2`. When I ran it from the command prompt it works. Stupid, I know. (^_^;) – AXO Dec 19 '17 at 08:53
  • 1
    I have created a bug report on YouTrack: https://youtrack.jetbrains.com/issue/PY-27648 (Unfortunately, I cannot delete this question in the bounty period.) – AXO Dec 19 '17 at 09:06

2 Answers2

2

This is not a bug about PyCharm as I cannot reproduce it with IDEA too. IDEA is using the same core as PyCharm using.

This is because of the way you launch your script. If you launch your script with Run, it works. If you launch it with Debug, it doesn't.

Because Run just run script in a terminal, but Debug will launch a debugger and connect that process to this debugger. The output you see is actually from debugger but not directly from your script. When you replace your process, debugger won't rebuild connection to that new-created process.

That's why you didn't get 2 outputted.

Sraw
  • 18,892
  • 11
  • 54
  • 87
  • What you say makes sense, but I'm positive that I'm using `Run`, not `Debug`. – AXO Dec 19 '17 at 10:01
  • I have tested it again with pycharm 2017.3 on ubuntu 16.04. It behaves like I described above. `Run` works but not `Debug`. – Sraw Dec 19 '17 at 10:14
  • 1
    Just curious, are you using Python 3.6, too? I've heard that PyCharm uses a different [debugging infrastructure for 3.6](https://blog.jetbrains.com/pycharm/2017/03/pycharm-2017-1/), maybe the test runner has been rewritten, too? – AXO Dec 19 '17 at 10:23
1

In Linux,there is a flag FD_CLOEXEC,you can test it by fcntl.fcntl(sys.stdout,fcntl.F_GETFD)

the behavior you described can reproduce in ubuntu16 by

import os
import sys
import fcntl
print(1)
ret = fcntl.fcntl(sys.stdout, fcntl.F_GETFD)
ret |= fcntl.FD_CLOEXEC
fcntl.fcntl(sys.stdout, fcntl.F_SETFD, ret)
os.execl(sys.executable, sys.executable, '-c', 'print(2)')
print(3)

So when you run in PyCharm,it must redirect the stdout and set the equivalent windows flag.

obgnaw
  • 3,007
  • 11
  • 25