【问题标题】:How to run a .plt file inside all subdirectories with gnuplot using python?如何使用 python 在 gnuplot 的所有子目录中运行 .plt 文件?
【发布时间】: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


【解决方案1】:

以下适用于我在 Win10 下使用 Python 3.6.3。我希望你能适应你的操作系统。

### start all gnuplot files in tree
import os, subprocess

directory = r'C:\Users\Test'
gnuplotpath = r'C:\Users\Programs\gnuplot\bin\gnuplot'

for root, subdirectories, files in os.walk(directory):
    for file in files:
        if file.endswith('.plt'):
            ffname = os.path.join(root,file)
            cmd = '{} -p "{}"'.format(gnuplotpath,ffname)
            plot = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
            plot.communicate()
            plot.wait()
            print(plot.returncode)
### end of code

【讨论】:

  • 我的 gnuplot 路径中有一个空格键。 cmd 给了我一个“...不被识别为内部或外部命令、可运行程序或批处理文件。”错误。除了在另一个没有空格的位置重新安装 gnuplot 之外,还有什么方法可以绕过它?
  • @PrajjwalDas 我会尝试将其另外放入单引号 gnuplotpath = r"'C:\Users\Programs\gnuplot\bin\gnuplot'"(不是我之前所说的双引号)。
猜你喜欢
  • 2010-10-13
  • 2016-08-20
  • 1970-01-01
  • 2014-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-04
  • 1970-01-01
相关资源
最近更新 更多