I wrote a bash script to create a setup file using
echo '...' > setup.py
and then in the next line I execute it using python setup.py build_ext --inplace. I replicated the first part with the write method of file objects in Python, my question is how can I replicate the second part in my Python script?
-
Why can't you just run the code in your script instead of piping it into another file?MattDMo– MattDMo2020-07-06 01:27:06 +00:00Commented Jul 6, 2020 at 1:27
1 Answer
What it seems like you're trying to do is not to give the Python interpreter commands, but actually to execute bash/shell commands from within a Python program execution.
When you open a terminal and run:
python setup.py build_ext --inplace
What happens is that a new Python process starts up and executes setup.py
Your goal is to do the same thing from a Python script. The generally accepted way to do this is to use the subprocess module: https://docs.python.org/3/library/subprocess.html
Something like
subprocess.run(["python", "setup.py", "build_ext", "--inplace"])
should work. Or if you really know what you're doing and you know that the input to the subprocess.run call won't ever get exposed to users (and thus hijacked) you could instead use:
subprocess.run("python setup.py build_ext --inplace", shell=True)
EDIT:
Alternatively if you want to dig deep into Python you could go look at how to call setuptools' build_ext command directly from code. Here's a good start in that direction. https://github.com/pypa/setuptools/blob/master/setuptools/command/build_ext.py#L83