【问题标题】:how to run python script from the console as if called from command prompt?如何从控制台运行 python 脚本,就像从命令提示符调用一样?
【发布时间】:2014-07-10 02:52:27
【问题描述】:

我将使用的 python 脚本(源代码here)在从命令行调用时会解析一些参数。但是,我无法在我的环境中访问 Windows 命令提示符 (cmd.exe)。我可以从 Python 控制台中调用相同的脚本吗?我宁愿不重写脚本本身。

【问题讨论】:

标签: python cmd console ipython spyder


【解决方案1】:

%run 是 IPython 中的一种魔法,它在 IPython 中将命名文件作为程序运行,几乎就像从 shell 中运行该文件一样。引用%run? 引用%run file args

这类似于在系统提示符python file args 下运行, 但它的优势在于为您提供 IPython 的回溯,以及 将所有变量加载到您的交互式命名空间中以供进一步使用 (除非使用 -p,见下文)。 (结束报价)

唯一的缺点是要运行的文件必须在当前工作目录中或沿PYTHONPATH 的某个位置。 %run 不会搜索 $PATH

%run 有几个选项,您可以从%run? 了解这些选项。例如:-p 在分析器下运行。

【讨论】:

    【解决方案2】:

    如果你可以进行系统调用,你可以使用:

    import os
    os.system("importer.py arguments_go_here")
    

    【讨论】:

      【解决方案3】:

      你想产生一个新的子进程。

      有一个模块:subprocess

      示例:

      基本:

      import sys
      from subprocess import Popen
      
      
      p = Popen(sys.executable, "C:\test.py")
      

      获取子进程的输出:

      import sys
      from subprocess import Popen, PIPE
      
      
      p = Popen(sys.executable, "C:\test.py", stdout=PIPE)
      stdout = p.stdout
      print stdout.read()
      

      有关详细信息,请参阅subprocess API 文档。

      【讨论】:

        猜你喜欢
        • 2017-03-10
        • 1970-01-01
        • 2021-10-12
        • 1970-01-01
        • 2021-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-25
        相关资源
        最近更新 更多