0

I have tow python files. From file1.py I want to call file2.py but with parameterized. Shell equivalent is: CALL file2.bat Input.txt

I tried using : os.system("file2.py Input.txt") but this is opening the text file in notepad. I want this file taken as an input in file2.py.

In file2.py, I'm checking the passed parameter as: print(f"First Argument : {sys.argv[0]}")

What could the proper way to do this?

Bogota
  • 401
  • 4
  • 15
  • Does this answer your question? [Calling an external command from Python](https://stackoverflow.com/questions/89228/calling-an-external-command-from-python) – fixatd May 12 '20 at 03:27
  • you need to run python files by calling `python .py` you can use subprocess in python `subprocess.run(['python', 'file2.py'])` but why not just import that other module and use all the behavior from it? – bherbruck May 12 '20 at 03:46
  • @TenaciousB in the command ```subprocess.run(['python', 'file2.py'])``` where can I give ```file1.txt``` as an Input? – Bogota May 12 '20 at 03:49
  • @fixatd tried using ```os.system``` but this is opening notepad. (not what I expect). Tried using ```subprocess.run("file2.py, Input.txt")``` but this is giving me error. Any corrections in the command? – Bogota May 12 '20 at 03:51
  • 1
    Would you be better off creating a function or class in file2.py that interacts with your .txt file and then importing that function or class into file1.py? – Lateralus May 12 '20 at 03:53
  • it would be `subprocess.run(['python', 'file2.py', 'input.txt'])` this would be the same as the command `$ python file2.py input.txt`. Each item in the subprocess list is a "space" separator in the console if that makes sense. When executing a python file from command line you need to use python as the first word – bherbruck May 12 '20 at 03:54

2 Answers2

0

Try the using subprocess:

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

This is kind of a "dirty" way of doing it IMO. I would personally import file2 and run the logic from the file1 module.

bherbruck
  • 2,167
  • 1
  • 6
  • 17
0

The problem here is not about os.system, but your operating system doesn't know to open .py files with python.

sys.executable contains full path of the currently running Python interpreter.

So the solution is:

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

It works with python, python3, if you are in your home directory and you type

 /usr/local/bin/python file1.py

Hardcoding the string "python", as in

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

is not a good advice.

Massimo
  • 3,171
  • 3
  • 28
  • 41
  • 1
    Using subprocess as this (https://stackoverflow.com/a/89243/12116796) listed benefits of subprocess over os.system. – Bogota May 12 '20 at 05:30
  • Yes, but os.system is not the root cause of your problem. An answer has to be strictly pertinent to the question; "good as a general advice" is off topic. – Massimo May 12 '20 at 06:50