简体   繁体   中英

How to pass arguments to exec() in python

I have converted my python script into exe using pyinstaller . This exe needs to call another python script. Now pyinstaller binds the python interpreter so we can call any other python script like below:

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

This will execute external_script.py . I want to perform external_script.py install using exec. So I also want to pass install as an argument. Something like below:

exec(open('external_script.py').read(), {'install'})

In above line of code, I am passing install as argument. But here I am not sure if this is correct syntax or not. Can anyone please tell me how can we pass arguments in exec python. Thanks

os.system is used to execute a cmd command

import os

cmd=input("type a  cmd statement here")
try:
    exec(os.system(cmd))
except Exception as e:
    print(e)

For you it will be

exec(os.system("external_script.py install"))

to pass arguments to exec() you need to pass dict as an argument for globals/locals not set .

exec(open('external_script.py'.read(),{'argv':'install'})

and it will create argv reference inside exec() scope, if you pass array to your external_script.py you will have to do add the following to the code

for i in argv: sys.argv.append(i)

note: if you use from sys import argv to import argv it will overwrite the value you passed with ['external_script.py']

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