Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有办法使用stdout的输出或重定向来运行python代码?_Python_Cmd_Head - Fatal编程技术网

有没有办法使用stdout的输出或重定向来运行python代码?

有没有办法使用stdout的输出或重定向来运行python代码?,python,cmd,head,Python,Cmd,Head,假设我有这样一个命令的输出: C:\> head type_test.py def greeting(name: str) -> str: return 'Hello ' + name print(greeting("John")) print("foo") print("bar") C:\> head type_test.py 6 def greeting(name: str) -> str: return 'Hello ' + name prin

假设我有这样一个命令的输出:

C:\> head type_test.py
def greeting(name: str) -> str:
    return 'Hello ' + name

print(greeting("John"))
print("foo")
print("bar")

C:\> head type_test.py 6
def greeting(name: str) -> str:
    return 'Hello ' + name

print(greeting("John"))
print("foo")
我想以某种方式将代码重定向到python解释器,以便输出为:

C:\> ???
Hello John
foo

我知道我必须将上一个命令的输出重定向到python,但python是否会像这样直接运行脚本?

只需执行以下操作。它对我有用

head -5 type_test.py | python

使用sys.stdin获取管道中的内容。假设我编写这个程序:

文件prog.py:

#!/usr/bin/python
import sys
x=sys.stdin.read()
print('hello '+x)
如果我这样做了:

$>chmod u+x prog.py
然后:

$>echo john | ./prog.py
我得到:

$>hello john

不。它仍然打印文件,而不是在python中执行。这绝对不是我想要做的。