【问题标题】:Pass a file as an input from one python to another将文件作为输入从一个 python 传递到另一个
【发布时间】:2020-08-27 19:01:57
【问题描述】:

我有两个 python 文件。从file1.py 我想调用file2.py 但参数化。 Shell 等效为:CALL file2.bat Input.txt

我尝试使用:os.system("file2.py Input.txt"),但这是在记事本中打开文本文件。我希望将此文件作为file2.py 中的输入。

file2.py 中,我将传递的参数检查为:print(f"First Argument : {sys.argv[0]}")

这样做的正确方法是什么?

【问题讨论】:

  • 这能回答你的问题吗? Calling an external command from Python
  • 你需要通过调用 python <filename>.py 来运行 python 文件,你可以在 python subprocess.run(['python', 'file2.py']) 中使用子进程,但是为什么不直接导入其他模块并使用它的所有行为呢?
  • @TenaciousB 在命令 subprocess.run(['python', 'file2.py']) 我可以在哪里提供 file1.txt 作为输入?
  • @fixatd 尝试使用 os.system 但这正在打开记事本。 (不是我所期望的)。尝试使用subprocess.run("file2.py, Input.txt"),但这给了我错误。命令中的任何更正?
  • 您最好在 file2.py 中创建一个与您的 .txt 文件交互的函数或类,然后将该函数或类导入 file1.py 中吗?

标签: python file batch-file parameters parameter-passing


【解决方案1】:

尝试使用subprocess:

import subprocess
subprocess.run(['python', 'file2.py', 'input.txt']) # this will be relative to the current directory

这是一种“肮脏”的 IMO 方式。我会亲自导入 file2 并从 file1 模块运行逻辑。

【讨论】:

    【解决方案2】:

    这里的问题不在于os.system,而是你的操作系统不知道用python打开.py文件。

    sys.executable 包含当前运行的 Python 解释器的完整路径。

    所以解决办法是:

     os.system(  sys.executable +  " file2.py Input.txt" )
    

    它适用于 python、python3,如果你在你的主目录中并且你输入

     /usr/local/bin/python file1.py
    

    硬编码字符串“python”,如

    subprocess.run(['python', ...
    

    不是一个好建议。

    【讨论】:

    • 使用子进程作为这个 (stackoverflow.com/a/89243/12116796) 列出了子进程相对于 os.system 的好处。
    • 是的,但 os.system 不是问题的根本原因。答案必须与问题严格相关; “作为一般建议好”是题外话。
    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    相关资源
    最近更新 更多