Python call multiple commands

六眼飞鱼酱① 提交于 2019-12-10 14:45:59

问题


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.


回答1:


You separate the lines with &

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



回答2:


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:


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




回答4:


Try to use subprocess.Popen and cwd

example:

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



回答5:


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.




回答6:


It’s simple, really. For Windows separate your commands with &, for Linux, separate them with ; You may want to put use string.replace, and if so, use the fallowing code:

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



回答7:


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




回答8:


Just use

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

I think you have got the idea what to do



来源:https://stackoverflow.com/questions/20042205/python-call-multiple-commands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!