我正在尝试使用 python 创建一个 PETSC 二进制文件。我尝试在 bash shell 上运行脚本,但出现错误
$ python -c 'print file.shape\n import sys,os\n sys.path.append(os.path.join(os.environ['PETSC_DIR'],'bin','pythonscripts '))\nimport PetscBinaryIO\nio=PetscBinaryIO.PetscBinaryIO()\nfile_fortran=file.transpose((2,1,0))\n io.writeBinaryFile('my_geometry.dat',(walls_fortran.rave1()).view (PetscBinaryIO.Vec),))'
Unexpected character after line continuation character.
我知道这是因为有一个额外的 \
但我的代码似乎没有。我尝试以交互方式运行 python,以使用 python -i 查找代码的哪一部分有问题
>>> walls=open('file.dat','r+')
>>> print walls.shape()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'file' object has no attribute 'shape'
我是 python 的新手,所以我知道这可能是一个明显的错误。但我似乎不知道这是关于什么的
感谢约翰的回答。 现在它识别出 PETSC_DIR 我得到了错误
>>> PETSC_DIR="/home/petsc-3.4.3"
>>> sys.path.append(os.path.join(os.environ["PETSC_DIR"],"bin","pythonscripts"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/UserDict.py", line 22, in __getitem__
raise KeyError(key)
KeyError: 'PETSC_DIR'</code>
它不识别 PETSC_DIR,即使我指定了它
请您参考如下方法:
为了便于说明,让我们摘录该 bash 脚本的一小段:
python -c 'print file.shape\n import sys,os\n'
在 bash 单引号字符串中,正如您在此处所用,字符“\n”表示反斜杠后跟“n”。 Python 将此视为“额外的反斜杠”,即使您的意思是将“\n”解释为换行符。这就是产生类型错误的原因
unexpected character after line continuation character
要解决此问题,请尝试:
python -c $'print file.shape\n import sys,os\n'
Bash 特殊对待 $'...'
字符串,除其他事项外,会将 \n
序列替换为 python 能够理解并知道如何处理的换行符过程。
(上面的代码仍然会报错,因为 file
没有 shape
属性。下面会详细介绍。)
还有其他问题。以这段摘录为例:
python -c 'sys.path.append(os.path.join(os.environ['PETSC_DIR'],'bin','pythonscripts'))'
在 bash 删除引号后,python 看到:
sys.path.append(os.path.join(os.environ[PETSC_DIR],bin,pythonscripts))
这行不通,因为 python 需要 PETSC_DIR
和 bin
以及 pythonscripts
被引用(使用单引号或双引号:python不在乎)。试试看:
python -c 'sys.path.append(os.path.join(os.environ["PETSC_DIR"],"bin","pythonscripts"))'
当 bash 看到单引号内有双引号时,它不会管它们。因此,python 将在需要的地方接收带引号的字符串。
总之,在我看来错误不是由您的 python 代码引起的,而是由 bash 在将它传递给 python 之前对您的 python 代码所做的操作引起的。
附录:至于 print walls.shape()
错误,其中 walls
是文件句柄,错误的意思是:文件句柄没有 shape
属性。可能您想使用 os.path.getsize(path)
os.path
模块中的函数以字节为单位获取文件大小?