简体   繁体   中英

How do I open another Python file within a file with a parameter/argument/variable attached?

I want to run another file from my main.py and also set the value of a variable in the main.py and "export it", so I can use it in the other file. But I absolutely don´t know how to do that. So that I can set a 'var = x[3]' in the main file and kinda "export" the variable into the file that I am opening like 'import otherfile.py(var = x[3])'

Thanks in advance

To import any variable from main file to otherfile you can use,

from main import*
Y = var 

That's how you can set var in main.py file and import or use it in otherfile.py.

You can use sys.argv to get arguments if you run the file from the command line so if you have the file:

import sys
print(sys.argv[0])

then open a command line and type python file.py hello it will print 'hello'.

As well, you can use os.system() to run command line functions from python so your first file could be:

import os
var = 'test'
os.system(f"python otherfile.py {var}")

and otherfile.py could be:

import sys
print(sys.argv[0])

then if you run the first file, a python window will open and print 'test'. Hope this was what you were looking for

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM