[英]Open python program within a different command-line-interface(CLI)?
I need a python script that opens another CLI and run it in there. 我需要一个python脚本,打开另一个CLI并在那里运行它。 Eg
例如
python C:\Python27\Scripts\script.py test
python /path/to/script_folder/script.py test
I need to support both Unix and Windows. 我需要支持Unix和Windows。
Any suggestions? 有什么建议么?
If you are you looking for running an interactive console in your script, then I'd use something like this: 如果您正在寻找在脚本中运行交互式控制台,那么我将使用以下内容:
import code
console = code.InteractiveConsole()
console.interact()
You can find more information in the code module documentation . 您可以在代码模块文档中找到更多信息。 In particular, you might be interested in the
runcode
and runsource
methods. 特别是,你可能有兴趣在
runcode
和runsource
方法。
If you are looking for running a script and continue after the script execution in a python shell, then I'd use something like this: 如果您正在寻找运行脚本并在python shell中执行脚本后继续,那么我将使用以下内容:
$ python -i <path_to_script>
After much deliberation, reading this question and others, I found the solution, had my "man am I dumb" moment, and in the end, this will do the trick: 经过深思熟虑,阅读这个问题和其他人,我找到了解决方案,让我的“男人是我愚蠢”的时刻,最后,这将成功:
command = r'start cmd.exe python "' + <script> + r'" [args]'
os.system(command)
The keyword there is "start." 关键字是“开始”。 It does magic that basically tells Windows that the file to execute has no relation to the actual caller, and viola, you have a new console.
它的魔力基本上告诉Windows要执行的文件与实际调用者无关,而中提琴,你有一个新的控制台。
I'm not sure about Unix, but I assume it'd be similar, using gnome-terminal somehow. 我不确定Unix,但我认为它类似,使用gnome-terminal以某种方式。
If I understand your question correctly, you want to: 如果我理解你的问题,你想:
Depending on whether point 3 must then leave the terminal window open, solutions can be very different. 根据点3是否必须使终端窗口打开,解决方案可能会有很大不同。
If you don't need the window open, just go for os.system
or subprocess
. 如果你不需要窗口打开,只是去
os.system
或subprocess
。 If you are only running a python script, you might get away with just specifying "python" as the executable, hence being cross-platform. 如果你只运行一个python脚本,你可能只是将“python”指定为可执行文件,因此是跨平台的。
If you do need the window open, you'll have to launch the specific shell+terminal, which is OS-specific (cmd.exe in Windows; in the unix world, /bin/sh, /bin/bash or whatever else, probably wrapped by xterm
). 如果你确实需要打开窗口,你必须启动特定于操作系统的特定shell +终端(Windows中的cmd.exe;在unix世界中,/ bin / sh,/ bin / bash或其他任何东西,可能由
xterm
包装)。
But to be honest, unless there's some very specific requirement to have a completely different terminal session open, what you should do is just import the second module and run it from the first, or read it in memory and then use exec
. 但说实话,除非有一些非常具体的要求让一个完全不同的终端会话打开,你应该做的只是导入第二个模块并从第一个模块运行它,或者在内存中读取它然后使用
exec
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.