首页 > 解决方案 > 获取TypeError:一元+的错误操作数类型:尝试使用子进程时的'str'

问题描述

我是 python 新手,如果我犯了任何愚蠢的错误,请原谅我。我一直在尝试弄清楚如何将命令传递给 cmd.exe 大约一个小时,并且每次都遇到错误。最近我收到了这个错误:TypeError:一元+的错误操作数类型:'str'。任何帮助将不胜感激,谢谢。

#defines a function to run BDP command with subprocess
def runcommand(command):
    """Runs command in cmd.exe"""
    import subprocess
    cmd = command
    returned_value = subprocess.call(cmd, shell=True)  
    # returns the exit code in unix
    print('returned value:', returned_value)

#defines a messagebox function to tell user what file to get
def messagebox(displayinfo):
    """Presents a messagebox telling the user to select a file"""
    from tkinter import messagebox
    messagebox.showinfo(message = displayinfo)

#Sets home to users home path eg C:/users/hsun2
from pathlib import Path
home = str(Path.home())
from tkinter import filedialog

#asks user for location of bfc file
messagebox('Select the bfc.nii.gz file')
bfcfile = filedialog.askopenfilename()
print(bfcfile)

#asks user for location of DTI.nii files
messagebox('Select your DTI.nii file')
dtinii = filedialog.askopenfilename()

#asks user for location of bval file
messagebox('Select bval file')
bvalfile = filedialog.askopenfilename()

#asks user for bvec file
messagebox('Select bvec file')
bvecfile = filedialog.askopenfilename()

output = r"'C:\Program Files\BrainSuite18a\bdp\bdp.exe' " + bfcfile 
+ " --FRT --FRACT --tensor --nii " + dtinii + " -g " + bvalfile 
+ " -b " + bvecfile

#print(output)

#runs bdp command with user input
#output = runcommand("'C:\Program Files\BrainSuite18a\bdp\bdp.exe' " + bfcfile +
#" --FRT --FRACT --tensor --nii " + dtinii + " -g " + bvalfile +
#" -b " + bvecfile)

退货

C:/Users/hsun2/Desktop/localBDP/MTS/testpy/MTS126028/BrainSuite/sagT1MPRAGE_we_normal.bfc.nii.gz
Traceback (most recent call last):
  File "bdpcommandtest.py", line 44, in <module>
    + " --FRT --FRACT --tensor --nii " + dtinii + " -g " + bvalfile
TypeError: bad operand type for unary +: 'str'


------------------
(program exited with code: 1)

Press any key to continue . . .

标签: python

解决方案


您的声明output应该在每行的末尾有行继续字符 \ 。您之前的代码不需要它,因为它被括在括号中。确保 \ 是该行中最后一个可见字符,您实际上正在做的是“转义”后面的换行符。调用str()是不必要的。

output = r"'C:\Program Files\BrainSuite18a\bdp\bdp.exe' " + bfcfile \
+ " --FRT --FRACT --tensor --nii " + dtinii + " -g " + bvalfile \
+ " -b " + bvecfile

对于 Windows 路径,您应该使用原始字符串(即r".."),使用 \(或使用 \\ 或 /)作为目录分隔符。在没有它的情况下,您的路径\b会被转换为退格键 (\x08)。


推荐阅读