Reputation: 849
I don't seem to get the output from running the compiled file on mac but it works on windows for some reason.
test.cpp
#include<iostream>
using namespace std;
int main()
{
cout << "Hello world" << endl;
return 0;
}
Python
p = subprocess.Popen([r"/usr/bin/g++", "-Wall", "-o", "test", 'test.cpp'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
p = subprocess.Popen(["test"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
Just return empty output :
(b'', b'')
Is there something I need to do extra to run on mac?
Upvotes: 2
Views: 3117
Reputation: 10726
The compilation went fine, it had no problems with your code, hence no output:
('', '')
Since you're using a POSIX system, a Mac, you tried to execute the binary without specifying './' in front of the generated binary file test
. Hence, your command should really be:
p = subprocess.Popen(["./test"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# ^^
p.communicate()
This should give you:
('Hello world\n', '')
As expected.
Another thing to note is that if you've added the binary's location to the $PATH
shell variable, you wouldn't need to type ./test
. However, because the binary isn't in the $PATH
, the shell couldn't find the executable - which is why you needed to specify the location of the binary **relative to the script's executing directory.
But, note that if you're doing this for cross-platform development (i.e. including support for Windows), that approach won't work - your approach will - i.e. using just the binary name but you'll have to change the paths of where the compiler is installed. If you're using Cygwin, then the approach shown above, will also work. If Mingw or VS, just the executable name will suffice, like in this example:
p = subprocess.Popen(["C:\\gcc\\bin\\g++.exe", "-Wall", "-o", "test.exe", 'test.cpp'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
p = subprocess.Popen(["test.exe"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#
p.communicate()
Reference:
Python subprocess output on windows?
Upvotes: 2
Reputation: 4685
In Mac and other UNIX based operating systems, to execute a file you have to precede a file name with ./
.
So to execute the file named test
you would have to say: ./test
using this knowledge, your code should be modified to the following:
p = subprocess.Popen([r"/usr/bin/g++", "-Wall", "-o", "test", 'test.cpp'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
p = subprocess.Popen(["./test"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
Upvotes: 1