[英]C program command line argument with spaces
My python program program.py
prints text with spaces, and my C program a.out
is only expecting a single command line argument. 我的python程序program.py
打印带有空格的文本,而我的C程序a.out
只期望一个命令行参数。 Why is there different behavior between these two methods... ie why does Method 1 work and not Method 2? 为什么这两种方法之间会有不同的行为……即为什么方法1起作用而方法2不起作用?
Method 1: 方法1:
# program.py
print("Hello world")
Terminal: 终奌站:
> ./a.out "$(python program.py)"
// Program successfully run
Method 2: 方法2:
# program.py
print("\"Hello world \"")
Terminal: 终奌站:
> ./a.out $(python program.py)
// Error- only one command line argument expected
Method 1: 方法1:
./a.out "$(python program.py)"
./a.out will use "$(python program.py)" as a string ./a.out将使用“ $(python program.py)”作为字符串
echo "$(python program.py)" prints "$(python program.py)"
Method 2: 方法2:
./a.out $(python program.py)
./a.out will use the result of $(python program.py) as an argument. ./a.out将使用$(python program.py)的结果作为参数。
echo $(python program.py)
will run the program, and what is printed will be used as an argument. echo $(python program.py)
将运行该程序,并且输出的内容将用作参数。
Because you have printed Hello world
, it will use Hello as the first argument, and world as the second argument. 因为您已经打印了Hello world
,它将使用Hello作为第一个参数,而world作为第二个参数。 it will result in something like 它会导致类似
./a.out Hello World
Apparently whenever you use a $something, it will always be split in several parameters if you have spaces in it. 显然,每当您使用$ something时,如果其中有空格,它将始终分为多个参数。 Just look at how $1 works, it's the same behavior. 看看$ 1的工作原理,它是相同的行为。 Then your $(command) will work the same. 然后,您的$(command)将起作用。 This is why you have to put quotes around it. 这就是为什么您必须在引号周围加上引号。
I tried: 我试过了:
ls $(echo '"Hello World!"')
It has the same behavior than your second method. 它的行为与第二种方法相同。
And this: 和这个:
ls "$(echo 'Hello World!')"
Is the same than your first method. 与您的第一种方法相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.