Run Python files using python

Asked

Viewed 112 times

0

Is there any way to run an x file in Python using a y file in Python, through Python codes?

1 answer

0

yes, this is inherent in programming languages.

The "right" way is to import the x.py file as a module.

see:

x py.

print('olá do modulo X')

def main():
    print('olá da função principal "x.main()"')


if __name__ == '__main__':
    main()

y. py

import x
# >>> 'olá do modulo X
x.main()
# >>> olá da função principal "x.main()"

Alternatively it is possible to run . py files as a separate process, using the Python interpreter, for this use the module subprocess:

y. py

import subprocess

subprocess.run("python x.py", shell=True)
# >>> olá do modulo X
# >>> olá da função principal "x.main()"

to see more:

https://docs.python.org/pt-br/3/tutorial/modules.html

https://docs.python.org/3/library/subprocess.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.