简体   繁体   English

使用 os.system 从 python 提示符执行命令

[英]Execute commands from python prompt using os.system

I am trying to execute a few commands using python shell to import a module ABC.我正在尝试使用 python shell 执行一些命令来导入模块 ABC。 For that I have created a python file test.py having the following lines:为此,我创建了一个 python 文件test.py ,其中包含以下几行:

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

Now I am trying to execute that file as follows - python test.py .现在我正在尝试按如下方式执行该文件 - python test.py Here, it runs till the 2nd line ie os.system('python') properly.在这里,它运行到第二行,即os.system('python')正确。 Then when it enters into the python prompt and there it remains stuck as it is not command prompt any more but python prompt.然后,当它进入 python 提示时,它仍然卡住,因为它不再是命令提示,而是 python 提示。 So how to execute the next command of importing the module ABC on the python prompt?那么如何在python提示符下执行下一条导入模块ABC的命令呢?

You can use the -c argument with python .您可以将-c参数与python一起使用。 For example,例如,

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

Command line and environment ( Python Documentation )命令行和环境( Python 文档

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.在您的终端中,当您运行 python 后跟脚本名称 (test.py) 时,您正在执行脚本的内容。 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.在该脚本中,当您使用 os.system('python') 调用“python”时,您将启动一个新的交互式 session,类似于从终端调用“python”。

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 :听起来您需要将所需的命令放入 Python 脚本中,例如my_imports.py

import ABC
import my_module

And run it from interactive Python with something like:并从交互式 Python 运行它,例如:

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.这将在当前上下文中执行脚本中的代码,使您可以在 Python CLI 上使用导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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