python - 迭代文件目录作为模块的输入

标签 python ipython jupyter

我有一个模块,我想在目录中的每个文件上运行。但是,当我使用每个文件作为输入迭代该目录时,模块找不到该文件,就好像循环中定义的变量实际上并不指向该文件一样。这是我尝试执行的代码:

import os as os

for file in os.listdir():
    if file.endswith('.fasta'):   
        !python ../iupred2a.py file long

非常感谢任何帮助。谢谢!

最佳答案

https://ipython.readthedocs.io/en/stable/interactive/reference.html#system-shell-access表示 shell 命令(例如,带有“!”前缀的行)按字面解释。当您键入“file”时,它会看到“file”,而不是 file 变量的值。

Any input line beginning with a ! character is passed verbatim (minus the !, of course) to the underlying operating system.

但它还表示您可以使用大括号或美元符号来“扩展”值。

IPython also allows you to expand the value of python variables when making system calls. Wrap variables or expressions in {braces}:

In [1]: pyvar = 'Hello world'
In [2]: !echo "A python variable: {pyvar}"
A python variable: Hello world
In [3]: import math
In [4]: x = 8
In [5]: !echo {math.factorial(x)}
40320

For simple cases, you can alternatively prepend $ to a variable name:

In [6]: !echo $sys.argv
[/home/fperez/usr/bin/ipython]
In [7]: !echo "A system variable: $$HOME"  # Use $$ for literal $
A system variable: /home/fperez

根据您的情况,请尝试 !python ../iupred2a.py $file long!python ../iupred2a.py {file} long

<小时/>

... 尽管如此,我认为最好只是导入您的其他Python 文件并直接调用其函数。这可能需要一些重新设计,因为importing from a file from one directory up这有点棘手,模块的命令行界面通常与其编程界面不同。

如果您可以将当前文件和 iupred2a.py 放入同一目录,并找出您实际想要调用的函数的名称,那么您的代码最终将类似于:

import os
import iupred2a as iup

for file in os.listdir():
    if file.endswith('.fasta'):   
        iup.do_the_thing(file, mode="long")

关于python - 迭代文件目录作为模块的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54833870/

相关文章:

python - PyEval_InitThreads 什么时候被调用?

python - 如何使用 Flask 使页面内容动态化?

ipython - 带有 bibtex 引文的 Jupyter 笔记本

version-control - PyCharm 中用于 Jupyter 笔记本的 VCS

python - 元素树xml

r - 使用 Jupyter Notebook 的 R Notebook 中的内核错误

python - 在 Python 中从控制台使用断点进行调试

python - 在 jupyter 中混合 python 输出和 Markdown

python - 环境变量中的 JUPYTER_PATH 不起作用

python - 在 Python 2.7 中解压 zip 字符串