On Ubuntu 22, using Python 3.10, I need to set up a VPN connection and analyze the response from the VPN server. I do this as follows:
connect_command = ['ip', 'netns', 'exec', 'vpn_test_namespace', 'ipsec', 'up', 'vpn_test_config']
connect_process = subprocess.Popen(connect_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
connect_output, connect_error = connect_process.communicate()
However, the process does not wait for completion, and communicate() executes instantly. As a result, connect_output and connect_error are empty. If I add a pause:
connect_command = ['ip', 'netns', 'exec', 'vpn_test_namespace', 'ipsec', 'up', 'vpn_test_config']
connect_process = subprocess.Popen(connect_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(3)
connect_output, connect_error = connect_process.communicate()
Or wait using a breakpoint, then everything is okay, and I see the result. What am I doing wrong?
I tried various methods recommended on StackOverflow or in Google, such as call(), check_call(), wait(), run(), but I was unable to achieve the desired result of making the script wait for the process to complete.
ip
is doing something funny, and that this cannot be reproduced with any other commands?ip
could be fixed to not play tricks like that. I don't have a way to repro that here but I can speculate that something like a shell wrapper which runs it in the background and then waits might work.