【问题标题】:Script to open another python file [closed]打开另一个python文件的脚本[关闭]
【发布时间】:2013-01-04 15:22:52
【问题描述】:

我有一个非常大的项目正在使用 python。我需要获取打开另一个 .py 文件的脚本。我曾尝试使用这样的脚本:

os.system("example.py arg")

如果文件中的脚本很小,例如函数打印或其他东西。但是,如果它们很长或其他东西,它们就不起作用!所以我需要一个真正有效的脚本并在命令提示符中打开 .py 文件。非常感谢!

【问题讨论】:

  • 应该始终有效。问题可能出在您的 example.py 文件中,但如果没有有关该问题的更多信息,我将无法帮助您。
  • 为什么不使用import?如果您尝试使用另一个文件中的函数,import 将起作用。
  • @iurisilvio 我无法提供有关该问题的更多信息,因为在评论中添加脚本时出现格式问题。而example.py中的问题是我没有shebang。感谢 Rashan Gandi,我现在有了。

标签: python windows function command


【解决方案1】:

如果你想从另一个文件中获取一个函数,你可以使用import

from example import my_funct # not that 'example' does NOT have '.py' following it
my_funct() # you can now use the function from the file.

或者,您可以只导入整个脚本:

import example
example.my_funct() # you have to specify that 'my_funct' is from 'example'

或者,你可以这样做:

from example import * # this imports all functions from 'example'
my_funct() # now you can use the function as you normally would

注意:要从模块中导入函数,您需要正确设置它。 This is how you add a function to your PYTHONPATH.

【讨论】:

    【解决方案2】:

    使用

    运行脚本
    os.system("example.py arg")
    

    需要

    • 脚本必须是可执行的(+x 位)
    • 脚本开头必须包含shebang“#!/usr/bin/python”

    另见Should I put #! (shebang) in Python scripts, and what form should it take?

    【讨论】:

    • 现在工作得很好!谢谢
    猜你喜欢
    • 2020-04-21
    • 2011-11-23
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2018-09-19
    • 2019-04-23
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多