Working with the terminal in Python. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Working with the terminal in Python.

Hi, I'm doing a script to automate my programming config. I'm writing a program that given a path and a .py file, it opens a new terminal at the path and executes the file. What module muast I use, subprecess or os? And I need a bit of help of wich functions to use. Tnx!

25th Jun 2019, 9:37 AM
guim casadellà cors
guim casadellà cors - avatar
3 Answers
+ 1
I see what you mean. The current working directory is forgotten as soon as the command runs which makes the second run fail. It sounds like you want to specify the "cwd" parameter instead of using the "cd" command. You'd want code like this: subprocess.run(["python3", file], cwd=path) Unlike "cd", your "cwd" may need to be an absolute path. In other words, it should start with something like "/" or "c:" instead of ".." or a subdirectory name.
25th Jun 2019, 3:03 PM
Josh Greig
Josh Greig - avatar
+ 1
Either one would work if you just want to run something and get its exit status so if that's all you need and anticipate needing, there aren't any strong arguments for one over the other. That being said I would use the subprocess module because it is more flexible, popular, and I would anticipate wanting something more advanced that os.system doesn't support. Something like this would run a command: import subprocess subprocess.run(["ls", "-l"]) With os.system, you can run "ls -l" also but it looks like you can't do slightly more advanced things like capturing standard output, standard error, run things asynchronously... without redirecting with temporary files. A more detailed comparison is discussed at: https://www.quora.com/Whats-the-difference-between-os-system-and-subprocess-call-in-JUMP_LINK__&&__Python__&&__JUMP_LINK Some discussion on how to use both are at: - subprocess: https://stackoverflow.com/questions/89228/calling-an-external-command-in-python - os.system: https://linuxhandbook.com/execute-shell-command-python/
25th Jun 2019, 11:58 AM
Josh Greig
Josh Greig - avatar
+ 1
With subprocess I've got a problem. I can't use properly the cd command. When I first do subprocess.run(["cd",path]) it works correctly. But if after this I run subprocess.run(["python3",file]) I'm not in the right directory because the previous command has already succeed. Do you see what I mean? Finally, I would like the script, before being run, the terminal path stays at the file directory. Tanks for the help! Josh Greig
25th Jun 2019, 12:43 PM
guim casadellà cors
guim casadellà cors - avatar