简体   繁体   English

Python : 想要使用在 python 中传递的命令行参数,作为将在 python 脚本中执行的另一个命令的参数

[英]Python : want to use the command line argument passed in python, as an argument to another command that will be executed within the python script

I am trying to write a python script where in the argument that is passed to this script, needs to be used as an argument to a command that will be executed in this script.我正在尝试编写一个 python 脚本,其中在传递给此脚本的参数中,需要用作将在此脚本中执行的命令的参数。 Executing this script on cygwin在 cygwin 上执行这个脚本

eg:- x.py file1例如:- x.py file1

inside x.py script:在 x.py 脚本中:

file = sys.argv[1]

data = os.popen('ar t file').read()

when this command is executed the value of file is not taken(ie file1),rather the 'file' variable is being considered as a file, and hence throws an error:filename 'file' cannot be found.Is it possible to pass the value of file as an argument to this command.当这个命令被执行时,文件的值没有被采用(即文件1),而是'file'变量被认为是一个文件,因此抛出一个错误:找不到文件名'文件'。是否可以通过文件的值作为此命令的参数。

Thanks, Akhilesh谢谢,阿基莱什

This is nothing to do with command arguments or passing them on, but a basic misunderstanding of strings.这与命令参数或传递它们无关,而是对字符串的基本误解。 You have a hard-coded string containing the word "file", you are not actually passing in the value of the file variable anywhere.您有一个包含“file”一词的硬编码字符串,您实际上并未在任何地方传递file变量的值。 You can use string substitution:您可以使用字符串替换:

data = os.popen('ar t {}'.format(file)).read()

or或者

data = os.popen('ar t %s' % file).read()

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

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