将参数传递给 os.system [英] Passing arguments into os.system

查看:50
本文介绍了将参数传递给 os.system的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过python执行以下命令.rtl2gds 是一个读取 2 个参数的工具:文件路径和模块名称

I need to execute the following command through python. rtl2gds is a tool which reads in 2 parameters: Path to a file and a module name

rtl2gds -rtl=/home/users/name/file.v -rtl_top=module_name -syn

我正在通过 argparse 从用户读取文件和模块名称的路径,如下所示:

I am reading in the path to the file and module name from the user through argparse as shown below:

parser = argparse.ArgumentParser(description='Read in a file..')    
parser.add_argument('fileread', type=argparse.FileType('r'), help='Enter the file path')    
parser.add_argument('-e', help='Enter the module name', dest='module_name')    
args = parser.parse_args()    
os.system("rtl2gds -rtl=args.fileread -rtl_top=args.module_name -syn")

但是当我调用 -rtl=args.fileread 时,读入 args.fileread 的文件路径并没有进入 os.system.相反,args.fileread 本身被假定为文件名,并且工具会标记错误.

But the file path that is read into args.fileread does not get in to the os.system when I call -rtl=args.fileread. Instead, args.fileread itself is being assumed as the file name and the tool flags an error.

我确信有一种方法可以将命令行参数读入 os.system 或其他一些函数(可能是子进程? - 但无法弄清楚如何).任何帮助表示赞赏.

I am sure there is a way to read in command line arguments into os.system or some other function (may be subprocess?- but couldnt figure out how). Any help is appreciated.

推荐答案

不要使用 os.system();subprocess 绝对是要走的路.

Don't use os.system(); subprocess is definitely the way to go.

您的问题是您希望 Python 理解您想要将 args.fileread 插入到一个字符串中.尽管 Python 如此强大,但它无法那样读懂你的心思!

Your problem though is that you expect Python to understand that you want to interpolate args.fileread into a string. As great as Python is, it is not able to read your mind like that!

改用字符串格式:

os.system("rtl2gds -rtl={args.fileread} -rtl_top={args.module_name} -syn".format(args=args)

如果您想将文件名传递给另一个命令,您应该不要使用 FileType 类型选项!你想要一个文件名,不是一个打开的文件对象:

If you want to pass a filename to another command, you should not use the FileType type option! You want a filename, not an open file object:

parser.add_argument('fileread', help='Enter the file path')

但是一定要使用 subprocess.call() 而不是 os.system():

But do use subprocess.call() instead of os.system():

import subprocess

subprocess.call(['rtl2gds', '-rtl=' + args.fileread, '-rtl_top=' + args.module_name, '-syn'])

如果 rtl2gds 正确实现了命令行解析,则 = 是可选的,您可以使用以下调用来代替,从而完全避免字符串连接:

If rtl2gds implements command line parsing properly, the = is optional and you can use the following call instead, avoiding string concatenation altogether:

subprocess.call(['rtl2gds', '-rtl', args.fileread, '-rtl_top', args.module_name, '-syn'])

这篇关于将参数传递给 os.system的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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