简体   繁体   English

使用来自另一个 python 文件的命令行参数调用 Python 文件

[英]Calling Python file with command line arguments from another python file

Currently my python code is called from command line as follows:目前我的python代码是从命令行调用的,如下所示:

C:\project-master>python myFile.py --plugin TestPlugin\migration -f "C:/Form1/All_2020-01-01.xsd"

Where myFile.py code needs commandline arguments: myFile.py 代码需要命令行参数的地方:

--plugin TestPlugin\migration
-f "C:/Form1/All_2020-01-01.xsd"

I have created a new python file called: Test.py .我创建了一个名为: Test.py的新 python 文件。 From Test.py file, how can I make a call to myFile.py along with the required arguments.Test.py文件中,如何调用myFile.py以及所需的参数。 For example-例如-

class Workflow:

    def Process(self):
        # How to make a call for below commandline from here: 
        # myFile.py --plugin TestPlugin\migration -f "C:/Form1/All_2020-01-01.xsd"

A = Workflow()
A.Process()

Python subprocess module is your friend on this one. Python subprocess 模块是你的朋友。

You can use the run() function of the subprocess module.您可以使用subprocess模块的run()函数。 Your execution command is given as a list of strings as the first arugment in run()您的执行命令以字符串列表的形式给出,作为run()的第一个参数

So in your case it should look like this:所以在你的情况下它应该是这样的:

import subprocess

subprocess.run(["python", "myFile.py", "--plugin", "TestPlugin\migration", "-f", "C:/Form1/All_2020-01-01.xsd"], shell=False)

You can put that line into your Process() method.您可以将该行放入Process()方法中。

Also have a look in the documentation if you want to catch the output eg如果您想捕获输出,请查看文档,例如

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM