简体   繁体   中英

Execute commands from python prompt using os.system

I am trying to execute a few commands using python shell to import a module ABC. For that I have created a python file test.py having the following lines:

import os
os.system('python')
os.system('import ABC')

Now I am trying to execute that file as follows - python test.py . Here, it runs till the 2nd line ie os.system('python') properly. Then when it enters into the python prompt and there it remains stuck as it is not command prompt any more but python prompt. So how to execute the next command of importing the module ABC on the python prompt?

You can use the -c argument with python . For example,

import os
os.system('python -c "import ABC"')

Command line and environment ( Python Documentation )

python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]

In your terminal, when you run python followed by the name of a script (test.py), you are executing the contents of the script. Within that script, when you call 'python' using os.system('python'), you are starting a new interactive session, similar to if you were to just call 'python' from your terminal.

import os
os.system('python -c "import ABC"')

It sounds like what you need is to put the commands you require in a Python script, eg my_imports.py :

import ABC
import my_module

And run it from interactive Python with something like:

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

That will execute the code in the script in the current context, making the imports available to you on the Python CLI.

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