Specifying arguments with spaces for running a python script

走远了吗. 提交于 2019-12-17 20:19:37

问题


How to run a python with arguments that would contain spaces? I am using MacOS

For example,

>python testProgram.py argument 1 argument 2

where "argument 1" is a single argument?


回答1:


where "argument 1" is a single argument.

You've basically answered your own question there, "argument 1" is indeed a single argument.

In other words, you need to quote it, something like one of:

python testProgram.py "argument 1" 'argument 2'

This isn't actually a Python issue however, it depends on the shell that you're using to run the Python script.

For example, with bash, there are differences between the single and double quotes, the most important of which is probably the various expansions like $HOME - the single quoted variant does not do those expansions.




回答2:


Enclose your parameters that contains spaces with double quotes

> python testProgram.py "argument 1" "argument 2"

this will work under Windows and Linux so chances are it'll be ok under Mac OS too.




回答3:


Or using subprocess from within python itself:

subprocess.call(['python','testProgram.py','argument 1','argument 2'])

But the other answers are more likely to be what you want.




回答4:


Try:

>python testProgram.py "argument 1" "argument 2"


来源:https://stackoverflow.com/questions/11894815/specifying-arguments-with-spaces-for-running-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!