如何根据命令行输入包含py文件? [英] How to include py file based on the command line input?

查看:111
本文介绍了如何根据命令行输入包含py文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的python脚本必须在代码中包含其他python脚本。我希望其他脚本作为命令行参数传递。
例如:
我的脚本是test.py,我想基于命令行输入在代码中包含first.py。
命令行输入

My python script has to include other python scripts in the code. And I want the other scripts to be passed as command line arguments. For example: My script is test.py, and I want to include first.py in my code based on the command line input. Command line input




python test.py first.py

python test.py first.py



在代码中,我要first.py导入就像这样:

In the code I want first.py to be imported as in:

首先导入

但是我找不到办法。我尝试使用optparse和fileInput,但事实并非如此。

But I can't figure out a way. I tried using optparse and fileInput, but they didn't turn out to be what I had intended.

推荐答案

我没有认为从参数导入模块是最佳做法,但是如果您确实想这样做,可以尝试以下代码:

I don't think it is best practice to import module from arguments, but if you really want to do that, could try below code:

import sys

for file_name in sys.argv[1:]:
    module_name = file_name.replace('.py', '')
    exec('import %s' % module_name)

这篇关于如何根据命令行输入包含py文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆