8
votes

I would like to invoke multiple commands from my python script. I tried using the os.system(), however, I'm running into issues when the current directory is changed.

example:

os.system("ls -l")
os.system("<some command>") # This will change the present working directory 
os.system("launchMyApp") # Some application invocation I need to do.

Now, the third call to launch doesn't work.

9
Did you try this with subprocess docs.python.org/2/library/… - Syed Habib M
chain commands like this os.system("ls -l && <some command> && launchMyApp") - vahid abdi

9 Answers

17
votes

os.system is a wrapper for Standard C function system(), and thus its argument can be any valid shell command as long as it fits into the memory reserved for environment and argument lists of a process.

So, separate those commands with semicolons or line breaks, and they will be executed sequentially in the same environment.

os.system(" ls -l; <some command>; launchMyApp")
os.system('''
ls -l
<some command>
launchMyApp
''')
7
votes

Try this

import os

os.system("ls -l")
os.chdir('path') # This will change the present working directory
os.system("launchMyApp") # Some application invocation I need to do.
3
votes

It’s simple, really. For Windows separate your commands with &, for Linux, separate them with ;.
str.replace is a very good way to approach the problem, used in the example below:

import os
os.system('''cd /
mkdir somedir'''.replace('\n', ';')) # or use & for Windows
2
votes

Each process has its own current working directory. Normally, child processes can't change parent's directory that is why cd is a builtin shell command: it runs in the same (shell) process.

Each os.system() call creates a new shell process. Changing the directory inside these processes has no effect on the parent python process and therefore on the subsequent shell processes.

To run multiple commands in the same shell instance, you could use subprocess module:

#!/usr/bin/env python
from subprocess import check_call

check_call(r"""set -e
ls -l
<some command> # This will change the present working directory 
launchMyApp""", shell=True)

If you know the destination directory; use cwd parameter suggested by @Puffin GDI instead.

1
votes

When you call os.system(), every time you create a subshell - that closes immediately when os.system returns (subprocess is the recommended library to invoke OS commands). If you need to invoke a set of commands - invoke them in one call. BTW, you may change working director from Python - os.chdir

1
votes

Try to use subprocess.Popen and cwd

example:

subprocess.Popen('launchMyApp', cwd=r'/working_directory/')
0
votes

Just use

os.system("first command\nsecond command\nthird command")

I think you have got the idea what to do

0
votes

os.system("ls -l && <some command>")

0
votes

You can change back to the directory you need to be in with os.chdir()