Linux 如何在 Python 中运行 bash 脚本,但又好像它是从另一个目录运行一样?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4834807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:40:55  来源:igfitidea点击:

How do I run a bash script inside Python, but act as if it's running from another directory?

pythonlinuxbashshellunix

提问by TIMEX

subprocess.call(["/home/blah/trunk/blah/run.sh", "/tmp/ad_xml", "/tmp/video_xml"])

I do this. However, inside my run.sh, I have "relative" paths. So, I have to "cd" into that directory, and then run the shell script. How do I do that?

我这样做。但是,在我的 run.sh 中,我有“相对”路径。所以,我必须“cd”到那个目录,然后运行shell脚本。我怎么做?

采纳答案by payne

Use the cwdargument to subprocess.call()

使用cwd参数subprocess.call()

From the docs here: http://docs.python.org/library/subprocess.html

从这里的文档:http: //docs.python.org/library/subprocess.html

If cwdis not None, the child's current directory will be changed to cwdbefore it is executed. Note that this directory is not considered when searching the executable, so you can't specify the program's path relative to cwd.

如果cwd不是 None,cwd则在执行之前将更改子级的当前目录 。请注意,搜索可执行文件时不考虑此目录,因此您不能指定程序相对于 cwd.

Example:

例子:

subprocess.call(["/home/blah/trunk/blah/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], cwd='/tmp')

回答by AlexJF

Well, you could use subprocess.Popenwith Shell = True and cwd = "Your desired working directory"

好吧,你可以使用subprocess.Popen和 Shell = True 和 cwd = "你想要的工作目录"

EDIT:It appears that call has the same arguments so just setting a cwd argument would work:

编辑:似乎调用具有相同的参数,因此只需设置 cwd 参数即可:

subprocess.call(["/home/blah/trunk/blah/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], cwd="PATH")

回答by Vincent

You can supply your working directory like this:

您可以像这样提供您的工作目录:

subprocess.call(["/home/blah/trunk/blah/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], cwd="/home/blah/trunk/blah")

subprocess.call(["/home/blah/trunk/blah/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], cwd="/home/blah/trunk/blah")