简体   繁体   English

如何使用python subprocess命令在不同目录中运行shell命令?

[英]How to run shell commands in different directory using python subprocess command?

I am trying to execute a shell command, for eg "ls" in a different directory from my python script.我正在尝试执行一个 shell 命令,例如在与我的 python 脚本不同的目录中的“ls”。 I am having issues changing the directory directly from the python code from subprocess.我在直接从子进程的 python 代码更改目录时遇到问题。

The subprocess methods all accept a cwd keyword argument. subprocess方法都接受cwd关键字参数。

import subprocess

d = subprocess.check_output(
    ['ls'], cwd='/home/you/Desktop')

Obviously, replace /home/you/Desktop with the actual directory you want.显然,将/home/you/Desktop替换为您想要的实际目录。

Most well-written shell commands will not require you to run them in any particular directory, but if that's what you want, this is how you do it.大多数编写良好的 shell 命令不会要求您在任何特定目录中运行它们,但如果这是您想要的,这就是您的方式。

If this doesn't solve your problem, please update your question to include the actual code which doesn't behave like you expect.如果这不能解决您的问题,请更新您的问题以包含行为不符合您预期的实际代码。

(Of course, a subprocess is a really poor way to get a directory listing, and ls is a really poor way to get a directory listing if you really want to use a subprocess. Probably try os.listdir('/home/you/Desktop') if that's what you actually want. But I'm guessing you are just providing ls as an example of an external command.) (当然,子进程是获取目录列表的非常糟糕的方法,如果您真的想使用子进程,则ls获取目录列表的非常糟糕的方法。可能尝试os.listdir('/home/you/Desktop')如果那是您真正想要的。但我猜您只是提供ls作为外部命令的示例。)

To add to tripleees excellent answer, you can solve this in 3 ways:要添加到三元组的优秀答案中,您可以通过 3 种方式解决此问题:

  1. Use subprocess' cwd argument使用子cwd参数
  2. Change dir before, using os.chdir之前更改目录,使用os.chdir
  3. Run the shell command to the exact dir you want, eg ls /path/to/dir OR cd /path/to/dir; ls将 shell 命令运行到您想要的确切目录,例如ls /path/to/dircd /path/to/dir; ls cd /path/to/dir; ls , but note that some shell directives (eg &&, ;) cannot be used without adding shell=True to the method call cd /path/to/dir; ls ,但请注意,如果不将shell=True添加到方法调用中,则无法使用某些 shell 指令(例如 &&、;)

PS as tripleee commented, using shell=True is not encouraged and there are a lot of things that should be taken into consideration when using it PS astripleee 评论说,不鼓励使用shell=True并且在使用时应该考虑很多事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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