我下载了一个由三个文件组成的python脚本:
file1.py
file2.py
file3.py
我通常使用如下命令调用脚本:
python file1.py arg1 arg2 -n arg3 arg4
现在我想从另一个python文件file4.py中调用这个脚本,但我不知道应该如何提供这些参数。
在file1.py中我有:
import time
import file2
import file3
def main():
variable1, variable2, variable3 = file2.parse_args()
...
run_simulation(variable1, variable2, variable3)
def run_simulation(variable1, variable2, variable3):
...
return
if __name__ == '__main__':
main()
和file2.parse_args()类似于:
def parse_args():
parser = argparse.ArgumentParser(
description="Desc1")
parser.add_argument("variable1", nargs="*", type=str,
help="Help")
parser.add_argument("-b", "--byte", nargs="*", type=str, metavar="byte",
help="Help2")
parser.add_argument("-e", "--exact", action="store_true",
help="Help3")
# Parse command line arguments and check for errors
args = parser.parse_args()
error_check_arguments(args)
[...]
variable1, variable2 = None, None
if not args.input:
variable1, variable2 = parse_cards(args.variable1, args.variable2)
return variable1, variable2, variable3
那么我应该在file4.py中放置什么代码才能运行这个脚本,就像我从命令行运行它一样?
答案 0 :(得分:0)
如果忽略文件2的参数解析功能,并且只是希望将参数从调用文件1传递给文件4中的函数,那么元组似乎是Pythonic。所以这段代码可以添加到文件1中:
For k = 1 To 6
If k <> 2 Then
Dim nc As New DataGridViewTextBoxColumn
nc.Name = ""
Myinputable.Columns.Add(nc)
Else
Myinputable.Columns.AddRange(combocol)
End If
Next k
' now add the rows and place the spreadsheet on the form
Myinputable.Rows.Add(nobj - 1)
Myinputable.Location = New Point(25, 50)
Myinputable.AutoSize = True
Me.Controls.Add(Myinputable)
FlowLayoutPanel1.Visible = True
Myinputable.Columns(0).Name = "Name"
Myinputable.Columns(0).HeaderText = "Name"
Myinputable.Columns(1).Name = "Type"
Myinputable.Columns(1).HeaderText = "Type"
Myinputable.Columns(2).Name = "LThresh"
Myinputable.Columns(2).HeaderText = "Lower Threshold"
'Myinputable.Columns(2).ValueType = co
Myinputable.Columns(3).Name = "UThresh"
Myinputable.Columns(3).HeaderText = "Upper Threshold"
Myinputable.Columns(4).Name = "ABMin"
Myinputable.Columns(4).HeaderText = "Abs. Minimum"
Myinputable.Columns(5).Name = "ABMax"
Myinputable.Columns(5).HeaderText = "Abs. Maximum "
Myinputable.Rows(0).Cells(0).Value = "Help"
If Myinputable.Capture = True Then
MsgBox(" damn ")
End If
End Sub
答案 1 :(得分:0)
更改main
函数,使其将变量作为参数。
def main(variable1, variable2m variable2):
...
将解析args的代码移动到if __name__ == '__main__'
块。
if __name__ == '__main__':
variable1, variable2, variable3 = file2.parse_args()
main(variable1, variable2, variable3)
您现在可以从其他模块调用main
函数:
from file1 import main
main('variable1', 'variable2', 'variable3')