Anonimous235
Anonimous235

Reputation: 1

Python interact with OS cmd

I would like to know if it was possible via the OS module to iterate on several lines with the command prompt Here is an example of what I would have liked to do but which does not work (non-persistent session):

from os import popen, system, getlogin

system(f'cd C:/Users/{getlogin()}')
print(popen('pip freeze'))

Upvotes: 0

Views: 356

Answers (1)

tttony
tttony

Reputation: 5092

I tested this on Windows and it worked with check_output from subprocess, using cmd /C to execute both commands and exit

from os import getlogin
from subprocess import check_output

cmd_str = fr'cmd.exe /C "cd C:\Users\{getlogin()} && pip freeze"'

output = check_output(cmd_str, shell=True).decode()
for line in output.split('\r\n'):
    print(line)

output:

absl-py==1.3.0
aiohttp==3.7.3
altgraph==0.17
astroid==2.4.2
astunparse==1.6.3
.....

Upvotes: 1

Related Questions