将文件作为输入从一个python传递到另一个python

问题描述 投票:0回答:2

我有两个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]}")

正确的方法是什么?

python file batch-file parameters parameter-passing
2个回答
0
投票

尝试使用subprocess

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

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


0
投票

这里的问题与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', ...

不是很好的建议。

© www.soinside.com 2019 - 2024. All rights reserved.