我想从我的python脚本调用多个命令。我尝试使用os.system(),但是,当更改当前目录时,我遇到了问题。
示例:
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.
现在,第三个调用启动无效。
您用&分隔行
os.system("ls -l & <some command> & launchMyApp")
尝试一下
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.
当您调用os.system()时,每次创建一个子shell时-在os.system返回时会立即关闭(建议使用subprocess来调用OS命令)。如果需要调用一组命令,请在一个调用中调用它们。顺便说一句,您可以从Python更改工作主管-os.chdir
每个进程都有自己的当前工作目录。通常,子进程无法更改父目录,这就是cd
是内置shell命令的原因:它在同一(shell)进程中运行。
每个os.system()
调用将创建一个新的Shell进程。在这些进程中更改目录对父python进程没有影响,因此对后续的shell进程也没有影响。
要在同一个shell实例中运行多个命令,可以使用subprocess
模块:
#!/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)
如果您知道目标目录; use cwd
parameter suggested by @Puffin GDI instead。
很简单,真的。对于Windows,请使用&分隔命令;对于Linux,请使用&分隔命令。您可能要使用use string.replace,如果是这样,请使用下面的代码:
cwd
您可以使用os.chdir()切换回您需要的目录
仅使用
import os
os.system(‘’’cd /
mkdir somedir’’’.replace(‘\n’, ‘; ‘) # or use & for Windows
我认为您已经知道该怎么办