r/learnpython • • Jun 05 '21

Running Terminal Commands With Python

I was wondering if there is a way to run terminal commands(ios) with python. Looking to change file names and other tasks that can be done in terminal ie "mv ~/Desktop/MyFile.rtf ~/Desktop/MyFile-old.rtf". Let me know!

1 Upvotes

5 comments sorted by

3

u/jeffrey_f Jun 05 '21

Just did this today...

import subprocess as sp

process = sp.Popen(["your_cmd"]...)
process.wait() #Waits for command completion

0

u/[deleted] Jun 06 '21

[deleted] — view deleted comment

1

u/jeffrey_f Jun 06 '21

I was trying to find that and can't get my googlefoo high enough to get an answer. Hopefully someone will answer that.

2

u/lowerthansound Jun 05 '21 edited Jun 06 '21

subprocess

Edit: Everyone is recommending the os module to move files, I recommend pathlib (it is neater).

0

u/[deleted] Jun 06 '21

[deleted] — view deleted comment

1

u/lowerthansound Jun 06 '21

For running the exact example from your post

import subprocess
subprocess.run(
    "mv ~/Desktop/MyFile.rtf ~/Desktop/MyFile-old.rtf",
    shell=True,
)

Not sure how this will deal with stdout and stderr though (read link if you want more information).

1

u/TabulateJarl8 TabulateJarl8 - GitHub & GitLab Jun 05 '21

There is a way to run terminal commands in python with the os and subprocess modules, but try to avoid it as much as possible, and try to use built in things. You can rename files in Python with os.rename() (or you can just move the file to the new name with a different built in function)