【问题标题】:Trying to control an application using its command line interface using python's subprocess module尝试使用 python 的 subprocess 模块使用其命令行界面控制应用程序
【发布时间】:2018-02-12 19:56:43
【问题描述】:

所以我使用了一个程序 DSI Studio,并且我正在做很多我想自动化的重复性任务。它有一个命令行界面,适用于我的命令

dsi_studio --action=trk -source=HarveyReg2.hdr.src.gz.odf4.f5rec.012fx.rdi.gqi.0.2.fib.gz --method=0 --
seed=leftprechiasm.nii.gz --roi=1.nii.gz --fiber_count=100 --output=track5.trk

它完全符合我的要求并输出一个文件。 但是当我尝试时

import subprocess

subprocess.call("dsi_studio --action=trk --source=HarveyReg2.hdr.src.gz.odf4.f5rec.012fx.rdi.gqi.0.2.fib.gz --method=0 --fa_threshold=0.00000 --turning_angle=70 --step_size=0.01 --smoothing=0 --min_length=0.0 --max_length=300.0 --initial_dir=0 --seed_plan=0 --interpolation=0 --thread_count=12 --seed=leftprechiasm.nii.gz --roi=1.nii.gz --fiber_count=100 --output=track4.trk", shell=True)

我得到返回码 1。如果我使用 subprocess.run,也会发生同样的事情。我用不同的排列四处游荡,但无济于事。我唯一能从中得到 0 返回码的是

subprocess.call('cd /d G:\Programs\dsi_studio_64', shell=True)

我尝试了,因为这是命令在 cmd 中工作所需的目录。但即使这样做了,它仍然不起作用。我是 python 的新手,我花了几天时间阅读像我这样的问题,但是当我尝试通过模板匹配来实现他们的解决方案时,我没有运气。

【问题讨论】:

  • 你得到什么错误?
  • 试试,使用 subprocess.Popen 它不会阻塞,允许你在进程运行时与它交互,或者继续你的 Python 程序中的其他事情。

标签: python shell subprocess


【解决方案1】:

每个子进程调用都有自己的 shell,因此您的 cd 实际上不会影响您以后的调用,因为您在错误的目录中,所以它会中断。试试

os.chdir("G:\Programs\dsi_studio_64")
subprocess.call("dsi_studio --action=trk --source=HarveyReg2.hdr.src.gz.odf4.f5rec.012fx.rdi.gqi.0.2.fib.gz --method=0 --fa_threshold=0.00000 --turning_angle=70 --step_size=0.01 --smoothing=0 --min_length=0.0 --max_length=300.0 --initial_dir=0 --seed_plan=0 --interpolation=0 --thread_count=12 --seed=leftprechiasm.nii.gz --roi=1.nii.gz --fiber_count=100 --output=track4.trk", shell=True)

你也可以使用cwd 参数来调用(),比如

subprocess.call("your long command", cwd="directory")

【讨论】:

  • 好吧,我仍然得到返回码 1,但它会生成文件,并且文件是它应该是的,所以我不会出汗。感谢您的帮助
【解决方案2】:

你可以使用 subprocess.Popen。

#!/usr/bin/env python
#  -*- coding: utf-8 -*-

import subprocess

def run_process(exe):
    'Define a function for running commands and capturing stdout line by line'
    p = subprocess.Popen(exe.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    return iter(p.stdout.readline, b'')


if __name__ == '__main__':
    for line in run_process("G:\Programs\dsi_studio_64\dsi_studio --action=trk --source=HarveyReg2.hdr.src.gz.odf4.f5rec.012fx.rdi.gqi.0.2.fib.gz --method=0 --fa_threshold=0.00000 --turning_angle=70 --step_size=0.01 --smoothing=0 --min_length=0.0 --max_length=300.0 --initial_dir=0 --seed_plan=0 --interpolation=0 --thread_count=12 --seed=leftprechiasm.nii.gz --roi=1.nii.gz --fiber_count=100 --output=track4.trk"):
        print(line)

【讨论】:

    猜你喜欢
    • 2014-09-18
    • 1970-01-01
    • 2014-09-30
    • 2015-06-02
    • 1970-01-01
    • 2010-11-23
    • 2021-06-01
    • 1970-01-01
    • 2011-05-07
    相关资源
    最近更新 更多