尝试使用python的子进程modu使用命令行接口控制应用程序

2024-06-23 18:51:39 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我使用一个程序DSI工作室,我做了很多重复的任务,我想自动化。它有一个命令行界面,我可以使用这个命令

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的新手,我花了几天时间阅读类似于我的问题,但是当我试图通过模板匹配实现他们的解决方案时,我没有运气


Tags: 命令srcsourcehdrcountactionseedsubprocess
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)

每个子进程调用都有自己的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)

也可以使用call()的cwd参数来完成,如

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

相关问题 更多 >

    热门问题