【发布时间】:2021-06-14 19:01:48
【问题描述】:
My directory structure looks like this,每个子目录的末尾都有一个不同的 .plt 文件。
我想使用 gnuplot 运行这些文件。这就是我所拥有的:
directory = "./"
for root, subdirectories, files in os.walk(directory):
for file in files:
if file.endswith('.plt'):
plot = subprocess.POpen(['gnuplot', '-p'], shell = True, stdin=subprocess.PIPE)
plot.communicate("load '%s'" % (file))
plot.wait()
print(plot.returncode)
但这会返回:
$ python3 messiah.py
Traceback (most recent call last):
File "messiah.py", line 115, in <module>
plot.communicate("load '%s'" % (file))
File "/usr/lib/python3.8/subprocess.py", line 1009, in communicate
self._stdin_write(input)
File "/usr/lib/python3.8/subprocess.py", line 958, in _stdin_write
self.stdin.write(input)
TypeError: a bytes-like object is required, not 'str'
-p: 1: gnuplot: not found
编辑: 在每个目录的末尾还有一个 .dat 文件,.plt 文件使用它来形成图形。这就是为什么我必须遍历两个文件所在的目录,然后在 cmd 中运行 gnuplot。如果我尝试从外部加载 .plt 文件,则会引发错误,提示找不到相应的 .dat 文件。
我试过了:
source = "/mnt/d/Darshana_Project/Data"
for root, subdir, files in os.walk(source):
if not subdir:
file = [fi for fi in files if fi.endswith('.plt')]
cmd1 = "cd \"%s\"" % (root)
cmd2 = "gnuplot -p \'%s\'" % (file[0])
command = cmd1+';'+cmd2
plot = subprocess.Popen(command, shell=True, encoding='utf8')
plot.wait()
但它只是给我一个:The system cannot find the path specified 递归地遍历所有子目录。
【问题讨论】:
-
在 gnuplot 中更改目录可能不是一个好主意。然后你得到你得到的混乱。只需给 gnuplot 文件的绝对路径,就像我在回答中所做的那样,例如
ffname = os.path.join(root,file)
标签: python subprocess gnuplot