0

I'm trying to execute file1.py from file2 .py by using exec function.

exec(open('file1.py').read())

Now I want to pass parameter target='target.yaml' to file1.py from exec function. How I can do that ? Please help

3
  • 2
    exec doesn't work like that, and exec is probably not what you should be using. You should probably be using import and defining and calling functions. Commented Jul 13, 2020 at 5:12
  • Executing a file does not take any arguments. Can you clarify how ˋfile1ˋ is supposed to receive them? Are you looking for command line arguments perhaps? Are you aware of the ˋsubprocessˋ module? Commented Jul 13, 2020 at 5:13
  • Basically i want to do write a script which will accept one file as parameter and execution o/p of this file will be yaml. 1) file2.py is a file which accepts one parameter file to be executed. now i passed file1.py as parameter to it and able to execute file1.py from file2.py. 2) now output of file1.py is yaml file but i want to make target path as parameter so that file can be created at passed path. Cannot use import file which i want to get execute can have different name Commented Jul 13, 2020 at 5:28

2 Answers 2

2

You can use subprocess module:

file1:

import subprocess

print("Running file1.py")
subprocess.run("python file2.py target.yaml", shell=True)
exit(0) # file2 will be opened in a new window


file2:

import sys
yaml_file = sys.argv[1]
print("Running file2.py : yaml target: "  + yaml_file)

output:
Running file1.py
Running file2.py : yaml target: target.yaml

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks i was not aware of subprocess module. Able to do it using subprocess instead of exec function,
1

While the other answer is a very good solution, if you are writing both files yourself you should consider importing one into the other and calling the function from the other file directly.

file1.py:

import otherfile

argument = "Hello world!"

otherfile.fancy_function(argument)

otherfile.py:

def fancy_function(arg):
    print(arg)

if __name__ == "__main__":
    # If the file is called directly like `python otherfile.py` this will be executed
    fancy_function("I have my own world too!")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.