简体   繁体   中英

Calling multiple commands using os.system in Python

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.

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
''')

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.

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

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 .

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

Try to use subprocess.Popen and cwd

example:

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

您可以使用os.chdir()改回您需要进入的目录

Just use

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

I think you have got the idea what to do

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM