簡體   English   中英

在python中調用外部函數

[英]calling an outside function in python

我試圖從if語句中的另一個文件返回(執行)函數。 我讀到return語句將不起作用,我希望有人會知道哪種語句將允許我調用外部函數。

該函數創建一個沙箱,但如果存在,我想傳遞if語句。

這是我使用的一小段代碼。

import mks_function  
from mksfunction import mks_create_sandbox  
import sys, os, time  
import os.path  

if not os.path.exists('home/build/test/new_sandbox/project.pj'):
 return mks_create_sandbox()  
else:  
 print pass  

假設您的功能bar位於Python路徑上名為foo.py的文件中。

如果foo.py包含以下內容:

def bar():
  return True

然后,您可以執行以下操作:

from foo import bar

if bar():
  print "bar() is True!"

讓我們看看文檔怎么說

return只能在語法上嵌套在函數定義中,而不能在嵌套的類定義中。

我想做的是:

from mksfunction import mks_create_sandbox  
import os.path

if not os.path.exists('home/build/test/new_sandbox/project.pj'):
    mks_create_sandbox()

我最近在python的最終項目中工作時,對此有很大的了解。 我也將致力於查看您的外部功能文件。

如果要調用模塊(實際上,同一文件之外的任何函數都可以視為模塊,我討厭指定過於精確的東西),則需要確保某些內容。 這是一個模塊的示例,我們稱它為my_module.py

# Example python module

import sys
# Any other imports... imports should always be first

# Some classes, functions, whatever...
# This is your meat and potatos

# Now we'll define a main function
def main():
    # This is the code that runs when you are running this module alone
    print sys.platform

# This checks whether this file is being run as the main script
#  or if its being run from another script
if __name__ == '__main__':
    main()
# Another script running this script (ie, in an import) would use it's own
#  filename as the value of __name__

現在,我想在另一個名為work.py的文件中調用整個函數。

import my_module

x = my_module
x.main()

您可能需要import包含功能的模塊,不是嗎?

當然,對您要實現的目標稍加精確將有所幫助。

“ return語句將不起作用”到底是什么意思?

您可以從其他文件import函數,然后像本地函數一樣調用它。

這取決於你的意思。 如果要創建靜態方法,則可以執行以下操作

class fubar(object):

    @classmethod
    def foo():
      return bar

fubar.foo() # returns bar

如果要運行外部流程,則可以使用子流程庫並執行

import subprocess
subprocess.popen("cmd echo 'test'",shell=true)

真的取決於你想做什么

你是說import嗎? 說,您的外部函數位於同一目錄中的mymodule.py中,您必須首先將其導入:

import mymodule
# or
from mymodule import myfunction

然后直接使用該函數:

if mymodule.myfunction() == "abc":
    # do something

或第二次導入:

if myfunction() == "abc":
    # do something

請參閱本教程

file1.py(注釋2個版本)

#version 1
from file2 import outsidefunction
print (outsidefunction(3))

#version 2
import file2
print (file2.outsidefunction(3))

#version 3
from file2 import *
print (outsidefunction(3))

file2.py

def outsidefunction(num):
    return num * 2

命令行: python file1.py

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM