[英]Pass a file as an input from one python to another
我有两个 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]}")
这样做的正确方法是什么?
尝试使用subprocess
:
import subprocess
subprocess.run(['python', 'file2.py', 'input.txt']) # this will be relative to the current directory
这是IMO的一种“肮脏”方式。 我会亲自导入 file2 并从 file1 模块运行逻辑。
这里的问题不是关于 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', ...
不是一个好建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.