python - 获取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 . . .
解决方案
您的声明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)。
推荐阅读
- android - 如何在视图模型类和前台服务之间传递数据
- firebase - 未处理的异常:NoSuchMethodError:在 null 上调用了方法“[]”。尝试调用:[](“is_ordered”)。检查空字段 Firebase
- c# - C# 将值添加到 JSON 文件而不更改初始 JSON 格式
- visual-studio - 新的 Visual Studio 2019 项目中缺少依赖项
- docker - 通过 Kubernetes 上的 nginx 入口中的服务公开容器中的基本路径
- laravel - github composer [InvalidArgumentException] 找不到匹配版本的包 Tohidda/payping
- javascript - JSXGraph - 多边形动画缓慢而粗糙
- python - Python Pandas 在 CSV 中删除并记录错误行
- exchange-server - 识别对禁用用户的每个共享邮箱具有“完全访问权限”和“代表发送”访问权限的所有用户
- python - 使用 python 和 kotlin 进行 Fernet 加密/解密