Пример #1
0
 def test_state_is_None(self):
     """Tests fileinput.fileno() when fileinput._state is None.
        Ensure that it raises RuntimeError with a meaningful error message
        and does not modify fileinput._state"""
     fileinput._state = None
     with self.assertRaises(RuntimeError) as cm:
         fileinput.fileno()
     self.assertEqual(("no active input()",), cm.exception.args)
     self.assertIsNone(fileinput._state)
Пример #2
0
 def test_state_is_not_None(self):
     """Tests fileinput.fileno() when fileinput._state is not None.
        Ensure that it invokes fileinput._state.fileno() exactly once,
        returns whatever it returns, and does not modify fileinput._state
        to point to a different object."""
     fileno_retval = object()
     instance = MockFileInput()
     instance.return_values["fileno"] = fileno_retval
     instance.fileno_retval = fileno_retval
     fileinput._state = instance
     retval = fileinput.fileno()
     self.assertExactlyOneInvocation(instance, "fileno")
     self.assertIs(retval, fileno_retval)
     self.assertIs(fileinput._state, instance)
Пример #3
0
 def test_state_is_not_None(self):
     """Tests fileinput.fileno() when fileinput._state is not None.
        Ensure that it invokes fileinput._state.fileno() exactly once,
        returns whatever it returns, and does not modify fileinput._state
        to point to a different object."""
     fileno_retval = object()
     instance = MockFileInput()
     instance.return_values["fileno"] = fileno_retval
     instance.fileno_retval = fileno_retval
     fileinput._state = instance
     retval = fileinput.fileno()
     self.assertExactlyOneInvocation(instance, "fileno")
     self.assertIs(retval, fileno_retval)
     self.assertIs(fileinput._state, instance)
Пример #4
0
import fileinput

for line in fileinput.input('example.py'):
  print(fileinput.fileno())


Пример #5
0
#!/usr/bin/python
from __future__ import print_function
import fileinput

for line in fileinput.input():
    meta = [
        fileinput.filename(),
        fileinput.fileno(),
        fileinput.filelineno(),
        fileinput.isfirstline(),
        fileinput.isstdin()
    ]
    print(*meta, end="")
    print(line, end="")
Пример #6
0
def evaluate_line(line_to_evaluate,debug):
    # evaluate the line for special exit condition
    check_if_exit(line_to_evaluate)

    # check if the string is changing directories
    test_cd = check_if_change_directory_command(line_to_evaluate)

    # initalize variable for piping
    shell_piping= check_if_pipes(line_to_evaluate)

    #initalize commands array
    commands = []
    # if there are pipe characters from the check_if_pipes method then set the commands array
    # to this array of commands. If not make the commands array an array of length 1 with the 
    # current line as the command.
    if shell_piping:
        commands = convert_line_to_array_of_commands(line_to_evaluate)
    else: 
        commands.append(line_to_evaluate)

    if debug:
        formatted_string = "here is the list of commands: {}".format(commands)
        os.write(2,formatted_string.encode())

    # iterate through the commands array and execute the commands. For shell re-direction and pipes
    # there needs to be file descriptor manipulation and we need to fork, duplicate, and close the processes
    # that execute these commands.
    command_index = 0
    for command in commands:
        # if the change directory function was true, skip the command loop and return to my_get_line
        if test_cd:
            break
        # Debugging code 
        if debug:
            os.write(2,("Here is the current command: {}\n".format(command)).encode())

        # get the process id of the parent    
        pid = os.getpid()

        # if there is piping call the start_pipe function and set the file descriptors and make them inhertiable 
        if shell_piping:
            file_discriptor_read, file_discriptor_write = start_pipe()
        else:
            file_discriptor_read = 0 
            file_discriptor_write = 1  

        # debugging code
        if debug:
            os.write(2, ("About to fork (pid: {})\n".format(pid)).encode())

        # fork the process
        run_commands = os.fork()


        if run_commands < 0:
            os.write(2, ("fork failed, returning {}\n".format(run_commands)).encode())
            sys.exit(1)
        
        # go and have the children attempt to run their commands
        elif run_commands == 0:                   # child
            if shell_piping:
                os.close(1) # redirect child's stdout
                os.set_inheritable(os.dup(file_discriptor_write), True)
            if debug:
                formatted_string = "Child: My pid== {}.  Parent's pid= {}\n".format(os.getpid(), pid).encode()
                os.write(2, formatted_string)

            # check if there is file redirection   
            test_redirect = check_if_redirecting(command)

            # convert the line that I've read using my_get_line and then converting to an array
            # and pass these as arguments to this loop to see if that binary exists in any
            # of the below paths
            if test_redirect:
                command = test_redirect

            args = convert_line_to_array(command) 

            # Get each of the path directories to search for binaries
            directories = re.split(":", os.environ['PATH'])
            for dir in directories: # try each directory in the path
                program_path = "{}/{}".format(dir, args[0]) # append the file trying to be executed to the path
                if debug:
                    os.write(2, ("Child:  ...trying to exec {}\n".format(program_path).encode()))
                try:
                    os.execve(program_path, args, os.environ)

                except FileNotFoundError:             # ...expected
                    pass                              # ...fail quietly
            

               
            for file_descriptor in (file_discriptor_read,file_discriptor_write):
                os.close(file_descriptor)

            formatted_string = "Whoa whoa whoa! Couldn't find: [{}] as a command! Try a different command \n".format(args[0])
            os.write(2, formatted_string.encode())
            #sys.exit(1)                 # terminate with error

        else: # parent (forked ok)
            childPidCode = os.wait()
            if shell_piping:
                os.close(0)
                os.set_inheritable(os.dup(file_discriptor_read), True)           
                for file_descriptor in (file_discriptor_write,file_discriptor_read):
                   os.close(file_descriptor)
                for line in fileinput.input():
                    os.write(1,("FD: %s From child: <%s>" % (fileinput.fileno(),line)).encode())                


            if debug:                          
                os.write(1, ("Parent: My pid=%d.  Child's pid=%d\n" % 
                            (pid, run_commands)).encode())

            if childPidCode[1] > 0:
                formatted_string = "Program terminated with exit code: {}\n".format(childPidCode[1])
                os.write(2, formatted_string.encode())
        command_index +=1

                
            
Пример #7
0
#!/usr/bin/env python3                     #标准注释,保证.py文件可在unix系统上运行
# -*- coding: utf-8  -*-                   #标准注释,表示.py文件都用标准UTF-8编码
#  'a test module'                            # 模块的文档注释,任何模块代码的第一个字符串都被视为模块的文档注释
__author__ = 'zxw'                     #作者名
import sys
import os                                 #        导入模块
import fileinput

for line in fileinput.input():
    meta = [fileinput.filename(),fileinput.fileno(),fileinput.isfirstline()]
    print(*meta,end=" ")
    print(line,end=" ")
Пример #8
0
import fileinput

for line in fileinput.input():
    meta = ["文件名:" + str(fileinput.filename()),
    " 文件描述符:" + str(fileinput.fileno()),
    " 行号:" + str(fileinput.filelineno()),
    " 首行:" + str(fileinput.isfirstline()),
    " 标准输入:" + str(fileinput.isstdin()) + " "]
    meta_ljust = [i.ljust(9) for i in meta]
    print(*meta_ljust, end="")
    print(line, end="")
Пример #9
0
#-*- coding: UTF-8 -*-
__author__ = 'mcxiaoke'

import os,fileinput
# 内部使用FileInput类实现
# fileinput 是一个从标准输入或者文件按行读入的工具类,默认是文本模式,一般的用法是

for line in fileinput.input(['file_input.py']):
    print fileinput.filename() # 文件名
    print fileinput.fileno() #文件描述符,int
    print fileinput.lineno() #总的行号
    print fileinput.filelineno() #当前文件的行号
    print fileinput.isstdin() # 是否标准输入
    print fileinput.isfirstline() # 是否是文件的第一行
    print fileinput.nextfile() # 关闭当前文件,开始读下一个文件
    print fileinput.close() # 关闭输入序列

Пример #10
0
 def update_event(self, inp=-1):
     self.set_output_val(0, fileinput.fileno())
Пример #11
0
#!/usr/bin/python
#-*-coding:UTF-8-*-

from __future__ import print_function
import sys
import fileinput


def get_content():
    return sys.stdin.readlines()


# print(get_content())

for line in fileinput.input():
    meta = [fileinput.filename(), fileinput.fileno(), fileinput.filelineno(), \
            fileinput.isfirstline(), fileinput.isstdin()]
    print(*meta, end="")
    print(line, end="")