S Andrew
S Andrew

Reputation: 7218

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

Upvotes: 4

Views: 8151

Answers (2)

Sandrin Joy
Sandrin Joy

Reputation: 1169

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

os.system("external_script.py install")

Where install is the argument to pass to external_script.py

Upvotes: 2

OZ_
OZ_

Reputation: 41

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']

Upvotes: 4

Related Questions