Reputation: 11218
I found how to use pip command in code:
import subprocess
subprocess.call(["pip", "freeze"])
It displays all packages in command prompt.
But it doesn't work this way:
import subprocess
subprocess.call(["pip", "freeze", ">", "requirements.txt"])
It doesn't writes it to file, it prints in console again.
How to run this command in the right way?
Upvotes: 1
Views: 2722
Reputation: 36033
Redirection is implemented in the shell/terminal, that means the command must be executed in the shell using shell=True
keyword argument. Otherwise subprocess executes the first item in the list and uses the rest as arguments to it. See the documentation for subprocess for more information.
subprocess.call("pip freeze > requirements.txt", shell=True)
Upvotes: 5
Reputation: 6590
Use this:
>>> with open('requirements.txt', 'w') as file_:
... subprocess.Popen(['pip', 'freeze'], stdout=file_).communicate()
...
or, call
if you prefer that
>>> with open('requirements.txt', 'w') as file_:
... subprocess.call(['pip', 'freeze'], stdout=file_)
Upvotes: 7