python - 如何在Python脚本中更改外部命令的目标目录

标签 python directory subprocess

早上好,
我正在编写一个 Python 脚本来比较两个安装程序。因此,我使用“sfk”(瑞士锉刀)技术来浏览解压缩的目录,包括浏览 *.jar 文件。
我的脚本如下所示:

  cmd_sfk1 = "sfk list -hidden -arc -time -size -tofile content_dir1.txt " + lv_inst_dir1
  cmd_sfk2 = "sfk list -hidden -arc -time -size -tofile content_dir2.txt " + lv_inst_dir2

  try:
    subprocess.call(cmd_sfk1)
  except Exception as ex:
    ...

  try:
    subprocess.call(cmd_sfk2)
  except Exception as ex:
    ...

如您所见,结果写入两个文件 (content_dir1.txt) 和 (content_dir2.txt),其想法是通过简单的文件比较即可了解两个目录/文件树之间的差异。

但是,这不起作用,因为文件中包含目录名称,以下是摘录:

...
2015-09-29 14:04:20          119 Dir1\InstallerData\...\MediaId.properties
2015-09-29 14:00:08          357 Dir1\InstallerData\...\\my.ini
...

该文件中“Dir1”的存在扰乱了比较。

我看到一个“简单”的解决方案:修改命令的目标目录,例如:

  cmd_sfk1 = "sfk list -hidden -arc -time -size -tofile ../content_dir1.txt " + "."
  cmd_sfk2 = "sfk list -hidden -arc -time -size -tofile ../content_dir2.txt " + "."

  try:
    subprocess.call(cmd_sfk1, target_directory=lv_inst_dir1)
  except Exception as ex:
    ...

  try:
    subprocess.call(cmd_sfk2, target_directory=lv_inst_dir2)
  except Exception as ex:
    ...

(有点像 DOS 批处理文件中的“pushd”和“popd”)
目的是最终得到以下 content_dir1.txt 内容:

...
2015-09-29 14:04:20          119 InstallerData\...\MediaId.properties
2015-09-29 14:00:08          357 InstallerData\...\\my.ini
...

(没有“Dir1”)
现在我的问题是:有人知道如何修改Python中子进程的目标目录吗?

谢谢
多米尼克

最佳答案

参数是cwd

subprocess.call(cmd_sfk1, cwd=lv_inst_dir1)

subprocess.Popen

关于python - 如何在Python脚本中更改外部命令的目标目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32903037/

相关文章:

c++ - 在 C++ 中重命名目录

整个文件夹的ffmpeg转换?

python - 如何使用 Python 子进程终止进程组

python - 使用子进程获取输出

python - 由于 unicode 解码错误,无法在 pandas 中打开 csv 文件

python - 如何修复类型 "object of type ' CategoricalDtype' has no len()"的错误?

python - Flask-Admin:路由到应用过滤器的模型 View

python - 语法错误: unexpected EOF while parsing when using function split in Python

Android:将图像存储到项目目录(文件)中?

java - 为什么 Java 创建的两个子进程表现不同?