【发布时间】: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 文件,你可以在 pythonsubprocess.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