在Python中使用os.system调用多个命令
我想从python脚本中调用多个命令。 我尝试使用os.system(),但是,在更改当前目录时遇到了问题 例如:在Python中使用os.system调用多个命令,python,unix,subprocess,command,Python,Unix,Subprocess,Command,我想从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. subprocess.Popen('l
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.
subprocess.Popen('launchMyApp', cwd=r'/working_directory/')
os.system(“ls-l”)
os.system(“”)#这将更改当前的工作目录
系统(“launchMyApp”)#我需要进行一些应用程序调用。
现在,对launch的第三个调用不起作用。当调用os.system()时,每次创建一个子shell时,都可以将其切换回需要使用的目录。
os.chdir()。如果需要调用一组命令,请在一次调用中调用它们。
顺便说一句,您可以将working director从Python-os.chdir更改为尝试使用和cwd
例如:
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.
subprocess.Popen('launchMyApp', cwd=r'/working_directory/')
每个进程都有自己的当前工作目录。通常,子进程不能更改父进程的目录,这就是为什么cd
是一个内置的shell命令:它在同一个(shell)进程中运行
每个os.system()
调用都会创建一个新的shell进程。更改这些进程内的目录不会影响父python进程,因此也不会影响后续的shell进程
要在同一个shell实例中运行多个命令,可以使用子流程
模块:
#!/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)
#/usr/bin/env python
从子流程导入检查调用
检查调用(r“”)集合-e
ls-l
#这将更改当前的工作目录
launchMyApp“”,shell=True)
如果您知道目标目录 只要使用
os.system(“第一个命令\n第二个命令\n第三个命令”)
我想您已经知道了要做什么是标准C函数的包装器,因此它的参数可以是任何有效的,只要它适合为环境和进程的参数列表保留的内存
因此,用分号或换行符分隔这些命令,它们将在相同的环境中顺序执行
os.system(" ls -l; <some command>; launchMyApp")
os.system(“ls-l;;launchMyApp”)
操作系统(“”)
ls-l
启动MyApp
''')
真的很简单。
对于Windows,用和分隔命令;对于Linux,用分隔命令代码>
str.replace
是解决问题的一种非常好的方法,在下面的示例中使用:
import os
os.system('''cd /
mkdir somedir'''.replace('\n', ';')) # or use & for Windows
试试这个
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(“ls-l&&”)
您是否尝试使用子流程链命令,如os.system(“ls-l&&&&launchMyApp”)
您是否可以使用子流程共享一个示例?我可能不知道更改的目录。有没有办法从上一次呼叫中获取更改过的目录?因此,如果需要从cmd获取输出,我可以在调用“launchMyApp”时传递该消息。也许您可以参考()p=subprocess.Popen(…)
和line=p.stdout.readline()