簡體   English   中英

我有兩個代碼腳本,我只想將一個特定的行從一個導入到另一個。 我該怎么做?

[英]I have two scripts of code and i want to import just one specific line from one into the other. How do i do it?

我想將一個特定的代碼行從一個腳本導入另一個腳本。 我不希望新代碼僅在一行中運行整個腳本。 我怎么做?

例如, from brcus import value

其中value等於完成的腳本中的數字,我想將該數字導入新腳本中,而舊腳本中的該行代碼為:“ value = 500”

每當您導入任何python模塊或軟件包並使用該模塊中的某些函數或值時,它都不會立即運行所有腳本。

你可以那樣做。

  1. 新腳本:-new.py
  2. 舊腳本:-old.py

如果在同一目錄中。

from old import value

a = value

我不建議您使用提取變量的方法。 相反,您應該查看實際的數據交換格式,例如jsonxml 它們被設計用來保存程序並使其易於訪問,同時(在某種程度上)是人類可讀的。 這些格式的解析器以及更多其他可用。

如果使用命令導入

from package import value

價值將成為您新代碼的一部分

例如

源代碼

value = 500
other = 400

命運

from Source import value
print (value)
>>500

命運

from Source import value
print (other)
>>NameError: name 'other' is not defined

我建議將要導入的零件移動到單獨的模塊中,並將其導入到其使用的所有模塊中。

my_var.py

 text = "Hello"

test.py

from my_var import text

def hello_friend(friend_name)
    print(text + " " + friend_name)

main.py

from my_var import text

print(text)

您還可以在導入的模塊中設置環境變量並檢查其值

test.py

import os

if os.environ['only_new_str'] != str(True):
    print("new_str is not calculated yet")
new_str = "Hello world"
if os.environ['only_new_str'] != str(True):
    print("new_str calculated")

main.py

import os
os.environ['only_new_str'] = str(True)
import test

print(test.new_str)

暫無
暫無

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

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